博客
关于我
OAuth2 + Gateway统一认证一步步实现(公司项目能直接使用),密码模式&授权码模式
阅读量:801 次
发布时间:2023-02-17

本文共 9260 字,大约阅读时间需要 30 分钟。

认证的具体实现

环境搭建

创建一个父工程,主要做版本控制。父工程的POM文件如下:

4.0.0
org.example
tl-authcenter
1.0-SNAPSHOT
jar
hs-common
hs-authcenter
1.8
UTF-8
1.8
1.8
8.0.15
1.1.10
3.5.3
3.3.2
2.7.0
2.3.12.RELEASE
Hoxton.SR12
2.2.9.RELEASE
org.springframework.boot
spring-boot-starter-parent
${spring-boot.version}
pom
import
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
com.alibaba.cloud
spring-cloud-alibaba-dependencies
${spring-cloud-alibaba.version}
pom
import
com.alibaba
druid-spring-boot-starter
${druid.version}
org.mybatis
mybatis
${mybatis.version}
com.baomidou
mybatis-plus-boot-starter
${mybatis-plus.version}
mysql
mysql-connector-java
${mysql-connector.version}
io.springfox
springfox-swagger2
${swagger2.version}
io.springfox
springfox-swagger-ui
${swagger2.version}
org.springframework.boot
spring-boot-starter-test
${spring-boot.version}
test
org.springframework.boot
spring-boot-configuration-processor
true
org.apache.maven.plugins
maven-jar-plugin
2.4

创建公共模块

创建一个公共模块hs-common,其POM文件如下:

4.0.0
hs-common
1.0-SNAPSHOT
jar
org.example
tl-authcenter
1.0-SNAPSHOT
UTF-8
com.alibaba
druid-spring-boot-starter
${druid.version}
org.springframework.data
spring-data-commons
org.projectlombok
lombok
org.apache.maven.plugins
maven-jar-plugin
2.4

数据库表结构

在数据库中创建oauth_client_details表,字段如下:

CREATE TABLE oauth_client_details (    client_id VARCHAR(128) NOT NULL,    resource_ids VARCHAR(256) DEFAULT NULL,    client_secret VARCHAR(256) DEFAULT NULL,    scope VARCHAR(256) DEFAULT NULL,    authorized_grant_types VARCHAR(256) DEFAULT NULL,    web_server_redirect_uri VARCHAR(256) DEFAULT NULL,    authorities VARCHAR(256) DEFAULT NULL,    access_token_validity INT(11) DEFAULT NULL,    refresh_token_validity INT(11) DEFAULT NULL,    additional_information VARCHAR(4096) DEFAULT NULL,    autoapprove VARCHAR(256) DEFAULT NULL,    PRIMARY KEY (client_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;

Spring Security配置

WebSecurityConfig类中,配置Spring Security:

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;@Configurationpublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {    @Autowired    private HushangUserDetailsService hushangUserDetailsService;    @Bean    public PasswordEncoder passwordEncoder() {        return new BCryptPasswordEncoder();    }    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.userDetailsService(hushangUserDetailsService);    }    @Bean    @Override    public AuthenticationManager authenticationManagerBean() throws Exception {        return super.authenticationManagerBean();    }    @Override    protected void configure(HttpSecurity http) throws Exception {        http.formLogin().permitAll()                .and().authorizeRequests()                .antMatchers("/oauth/**").permitAll()                .anyRequest().authenticated()                .and().logout().permitAll()                .and().csrf().disable();    }}

用户DetailsService实现

创建HushangUserDetailsService实现:

import com.hs.authcenter.entity.User;import com.hs.authcenter.entity.UserDetailsWrap;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Component;@Component@Slf4jpublic class HushangUserDetailsService implements UserDetailsService {    @Autowired    private PasswordEncoder passwordEncoder;    @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {        UserDetails user = User                .withUsername(username)                .password(passwordEncoder.encode("123456"))                .roles("user")                .build();        return user;    }}

JWT配置

创建JwtTokenEnhancer实现:

import com.hs.common.entity.UserDetailsWrap;import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;import org.springframework.security.oauth2.common.OAuth2AccessToken;import org.springframework.security.oauth2.common.OAuth2Authentication;import org.springframework.security.oauth2.provider.TokenEnhancer;import java.util.HashMap;import java.util.Map;@Componentpublic class JwtTokenEnhancer implements TokenEnhancer {    @Override    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {        UserDetailsWrap userDetails = (UserDetailsWrap) authentication.getPrincipal();        Map
additionalInfo = new HashMap<>(); additionalInfo.put("userId", userDetails.getUser().getId()); additionalInfo.put("userName", userDetails.getUser().getUsername()); Map
retMap = new HashMap<>(); retMap.put("additionalInfo", additionalInfo); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(retMap); return accessToken; }}

网关配置

在网关中添加认证过滤器,确保所有请求经过认证:

import com.hs.gateway.filter.AuthenticationFilter;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.gateway.filter.GlobalFilter;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class GatewayApplication {    public static void main(String[] args) {        SpringApplication.run(GatewayApplication.class, args);    }    @Bean    public GlobalFilter authenticationFilter() {        return new AuthenticationFilter();    }}

通过以上配置,完成了认证服务的搭建,包括依赖管理、数据库配置、Spring Security配置、JWT实现以及网关集成等内容。

转载地址:http://eknfk.baihongyu.com/

你可能感兴趣的文章
Objective-C实现combinationSum组合和算法(附完整源码)
查看>>
Objective-C实现combinations排列组合算法(附完整源码)
查看>>
Objective-C实现combine With Repetitions结合重复算法(附完整源码)
查看>>
Objective-C实现combine Without Repetitions不重复地结合算法(附完整源码)
查看>>
Objective-C实现conjugate gradient共轭梯度算法(附完整源码)
查看>>
Objective-C实现connected components连通分量算法(附完整源码)
查看>>
Objective-C实现Connected Components连通分量算法(附完整源码)
查看>>
Objective-C实现Convex hull凸包问题算法(附完整源码)
查看>>
Objective-C实现convolution neural network卷积神经网络算法(附完整源码)
查看>>
Objective-C实现convolve卷积算法(附完整源码)
查看>>
Objective-C实现coulombs law库仑定律算法(附完整源码)
查看>>
Objective-C实现counting sort计数排序算法(附完整源码)
查看>>
Objective-C实现countSetBits设置位的数量算法(附完整源码)
查看>>
Objective-C实现currency converter货币换算算法(附完整源码)
查看>>
Objective-C实现cycle sort循环排序算法(附完整源码)
查看>>
Objective-C实现data transformations数据转换算法(附完整源码)
查看>>
Objective-C实现datamatrix二维码识别 (附完整源码)
查看>>
Objective-C实现DateToDay 方法算法(附完整源码)
查看>>
Objective-C实现DBSCAN聚类算法(附完整源码)
查看>>
Objective-C实现DBSCAN聚类算法(附完整源码)
查看>>