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

你可能感兴趣的文章
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
node.js 配置首页打开页面
查看>>
node.js+react写的一个登录注册 demo测试
查看>>
Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
查看>>
nodejs libararies
查看>>
nodejs-mime类型
查看>>
nodejs中Express 路由统一设置缓存的小技巧
查看>>
Node入门之创建第一个HelloNode
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>