當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringCloud 基于OAth2.0 搭建认证授权中心_02
生活随笔
收集整理的這篇文章主要介紹了
SpringCloud 基于OAth2.0 搭建认证授权中心_02
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 一、數(shù)據(jù)庫部分
- 1. 創(chuàng)建數(shù)據(jù)庫
- 2. 初始化數(shù)據(jù)腳本
- 二、搭建maven父工程認證授權(quán)模塊
- 2.1. 創(chuàng)建一個maven項目
- 2.2. 引入依賴
- 三、搭建認證授權(quán)模塊
- 3.1. 創(chuàng)建一個子maven項目
- 3.2. 引入依賴
- 3.3. 增加application.yaml
- 3.4. 增加數(shù)據(jù)庫實體
- 3.5. 增加接口
- 3.6. 增加用戶讀取實現(xiàn)類
- 3.7. 增加授權(quán)服務(wù)配置
- 3.8. 增加web安全攔截
- 3.9. 增加controller
- 3.10. 啟動類添加注解
一、數(shù)據(jù)庫部分
1. 創(chuàng)建數(shù)據(jù)庫
創(chuàng)建一個名稱為Auth-serv數(shù)據(jù)庫
2. 初始化數(shù)據(jù)腳本
create table oauth_client_details (client_id VARCHAR(256) PRIMARY KEY,resource_ids VARCHAR(256),client_secret VARCHAR(256),scope VARCHAR(256),authorized_grant_types VARCHAR(256),web_server_redirect_uri VARCHAR(256),authorities VARCHAR(256),access_token_validity INTEGER,refresh_token_validity INTEGER,additional_information VARCHAR(4096),autoapprove VARCHAR(256) );create table oauth_client_token (token_id VARCHAR(256),token BLOB,authentication_id VARCHAR(256) PRIMARY KEY,user_name VARCHAR(256),client_id VARCHAR(256) );create table oauth_access_token (token_id VARCHAR(256),token BLOB,authentication_id VARCHAR(256) PRIMARY KEY,user_name VARCHAR(256),client_id VARCHAR(256),authentication BLOB,refresh_token VARCHAR(256) );create table oauth_refresh_token (token_id VARCHAR(256),token BLOB,authentication BLOB );create table oauth_code (code VARCHAR(256), authentication BLOB );create table oauth_approvals (userId VARCHAR(256),clientId VARCHAR(256),scope VARCHAR(256),status VARCHAR(10),expiresAt TIMESTAMP,lastModifiedAt TIMESTAMP );-- customized oauth_client_details table create table ClientDetails (appId VARCHAR(256) PRIMARY KEY,resourceIds VARCHAR(256),appSecret VARCHAR(256),scope VARCHAR(256),grantTypes VARCHAR(256),redirectUrl VARCHAR(256),authorities VARCHAR(256),access_token_validity INTEGER,refresh_token_validity INTEGER,additionalInformation VARCHAR(4096),autoApproveScopes VARCHAR(256) );create table user (id int auto_incrementprimary key,passwd varchar(265) not null,user_name varchar(256) not null,user_role varchar(255) not null );INSERT INTO `user` VALUES ('1', '$2a$10$9zmzrQoHPe2LvU/ciYOh7eh0vpThlG0jfVnd95t/McLyLb9t5N3zG', 'ziya', 'ADMIN'); INSERT INTO `oauth_client_details` VALUES ('app', 'app', '$2a$10$by3F74LZAxBQLXCbESOS/eew8/7skdxvx5QdcJAMddfLISizAOXAe', 'web', 'implicit,client_credentials,authorization_code,refresh_token,password', 'http://www.baidu.com', 'ROLE_USER', null, null, null, null);二、搭建maven父工程認證授權(quán)模塊
2.1. 創(chuàng)建一個maven項目
創(chuàng)建一個名稱為eshop-parent的maven父工程
2.2. 引入依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><packaging>pom</packaging><description>電商父模塊,所有子模塊依賴傳遞</description><modules><module>order-serv</module><module>product-serv</module><module>user-serv</module><module>stock-serv</module><module>shopcart-serv</module><module>auth-serv</module></modules><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.gblfy</groupId><artifactId>eshop-parent</artifactId><version>1.0-SNAPSHOT</version><!--https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E--><properties><java.version>1.8</java.version><spring.cloud-version>Hoxton.SR9</spring.cloud-version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--服務(wù)注冊發(fā)現(xiàn)--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring.cloud-version}</version><type>pom</type><scope>import</scope></dependency><!--spring-cloud-alibaba 版本控制--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>2.2.6.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement> </project>其他子模塊可以先忽略
三、搭建認證授權(quán)模塊
3.1. 創(chuàng)建一個子maven項目
3.2. 引入依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><artifactId>auth-serv</artifactId><name>auth-serv</name><parent><groupId>com.gblfy</groupId><artifactId>eshop-parent</artifactId><version>1.0-SNAPSHOT</version></parent><dependencies><!--Lombok引入--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- Spring Boot JPA 依賴 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId></dependency></dependencies></project>3.3. 增加application.yaml
spring:datasource:url: jdbc:mysql://localhost:3306/auth-servusername: rootpassword: 123456main:allow-bean-definition-overriding: trueapplication:name: auth-servcloud:nacos:discovery:server-addr: 127.0.0.1:8848 server:port: 50003.4. 增加數(shù)據(jù)庫實體
package com.gblfy.authserv.entity;import lombok.Data;import javax.persistence.*;@Entity @Table(name = "user") @Data public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;@Column(name = "passwd")private String passwd;@Column(name = "user_name")private String userName;@Column(name = "user_role")private String userRole;public Integer getId() {return id;}}3.5. 增加接口
Repository 里面只需要寫一個sql,通過用戶名查詢用戶
package com.gblfy.authserv.mapper;import com.gblfy.authserv.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;```bash @Repository public interface UserRepository extends JpaRepository<User, Integer> {User queryByUserName(String userName); }3.6. 增加用戶讀取實現(xiàn)類
package com.gblfy.authserv.service;import com.gblfy.authserv.entity.User; import com.gblfy.authserv.mapper.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; 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.Service;@Service("UserDetailServiceImpl") public class UserDetailServiceImpl implements UserDetailsService {@Autowiredprivate UserRepository userRepository;@Overridepublic UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {//獲取本地用戶User user = userRepository.queryByUserName(userName);if (user != null) {//返回oauth2的用戶return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPasswd(),AuthorityUtils.createAuthorityList(user.getPasswd()));} else {throw new UsernameNotFoundException("用戶[" + userName + "]不存在");}} }3.7. 增加授權(quán)服務(wù)配置
package com.gblfy.authserv.config;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.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;import javax.sql.DataSource;@Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailService;// 認證管理器@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate DataSource dataSource;/*** access_token存儲器* 這里存儲在數(shù)據(jù)庫,大家可以結(jié)合自己的業(yè)務(wù)場景考慮將access_token存入數(shù)據(jù)庫還是redis*/@Beanpublic TokenStore tokenStore() {return new JdbcTokenStore(dataSource);}/*** 從數(shù)據(jù)庫讀取clientDetails相關(guān)配置* 有InMemoryClientDetailsService 和 JdbcClientDetailsService 兩種方式選擇*/@Beanpublic ClientDetailsService clientDetails() {return new JdbcClientDetailsService(dataSource);}/*** 注入密碼加密實現(xiàn)器*/@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}/*** 認證服務(wù)器Endpoints配置*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {//如果需要使用refresh_token模式則需要注入userDetailServiceendpoints.userDetailsService(userDetailService);endpoints.authenticationManager(this.authenticationManager);endpoints.tokenStore(tokenStore());}/*** 認證服務(wù)器相關(guān)接口權(quán)限管理*/@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {security.allowFormAuthenticationForClients() //如果使用表單認證則需要加上.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");}/*** client存儲方式,此處使用jdbc存儲*/@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.withClientDetails(clientDetails());} }3.8. 增加web安全攔截
package com.gblfy.authserv.config;import com.gblfy.authserv.service.UserDetailServiceImpl; 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.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Override@Bean("UserDetailServiceImpl")public UserDetailsService userDetailsService(){return new UserDetailServiceImpl();}@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}/*** 認證管理* @return 認證管理對象* @throws Exception 認證異常信息*/@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService()).passwordEncoder(new PasswordEncoder() {//密碼加密@Overridepublic String encode(CharSequence charSequence) {BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();return passwordEncoder.encode(charSequence);}@Overridepublic boolean matches(CharSequence charSequence, String s) {BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();boolean res = passwordEncoder.matches(charSequence, s);return res;}});}/*** http安全配置* @param http http安全對象* @throws Exception http安全異常信息*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and().cors().and().csrf().disable();}@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/error","/static/**","/v2/api-docs/**","/swagger-resources/**","/webjars/**","/favicon.ico");} }3.9. 增加controller
package com.gblfy.authserv.controller;import com.gblfy.authserv.entity.User; import com.gblfy.authserv.mapper.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import java.security.Principal;@RestController @RequestMapping("user") public class UserController {@Autowiredpublic UserRepository userRepository;@GetMapping("getByName")public User getByName(){return userRepository.queryByUserName("ziya");}/*** 獲取授權(quán)的用戶信息* @param principal 當前用戶* @return 授權(quán)信息*/@GetMapping("current/get")public Principal user(Principal principal){return principal;} }3.10. 啟動類添加注解
增加Application啟動類 注意@EnableResourceServer
package com.gblfy.authserv;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;@SpringBootApplication @EnableResourceServer @EnableDiscoveryClient public class AuthServApplication {public static void main(String[] args) {SpringApplication.run(AuthServApplication.class, args);}}總結(jié)
以上是生活随笔為你收集整理的SpringCloud 基于OAth2.0 搭建认证授权中心_02的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: docker sonarqube:7.7
- 下一篇: 使用Vant完成DatetimePick