博客
关于我
OAuth2 + Gateway统一认证一步步实现(公司项目能直接使用),密码模式&授权码模式
阅读量:795 次
发布时间: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/

你可能感兴趣的文章
nslookup 的基本知识与命令详解
查看>>
NSNumber与NSInteger的区别 -bei
查看>>
NSOperation基本操作
查看>>
NSRange 范围
查看>>
NSSet集合 无序的 不能重复的
查看>>
NSURLSession下载和断点续传
查看>>
NSUserdefault读书笔记
查看>>
NS图绘制工具推荐
查看>>
NT AUTHORITY\NETWORK SERVICE 权限问题
查看>>
NT symbols are incorrect, please fix symbols
查看>>
ntelliJ IDEA 报错:找不到包或者找不到符号
查看>>
NTFS文件权限管理实战
查看>>
ntko web firefox跨浏览器插件_深度比较:2019年6个最好的跨浏览器测试工具
查看>>
ntko文件存取错误_苹果推送 macOS 10.15.4:iCloud 云盘文件夹共享终于来了
查看>>
ntp server 用法小结
查看>>
ntpdate 通过外网同步时间
查看>>
ntpdate同步配置文件调整详解
查看>>
NTPD使用/etc/ntp.conf配置时钟同步详解
查看>>
NTP及Chrony时间同步服务设置
查看>>
NTP服务器
查看>>