先提一句
最新發現用idea創建springboot工程,他給的版本是2.2.4,如果你的maven用的是阿里雲鏡像的話,會報找不到!阿里雲應該還沒有同步這個版本,請降到2.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>oauth</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>oauth</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
連接redis
Linux或者Windows要有redis,我這裏裝在了Windows環境下
spring.redis.host=localhost
spring.redis.port=6379
配置授權服務
package com.example.oauth.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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.token.store.redis.RedisTokenStore;
/**
* @description:
* 授權服務器
* @author: Leo
* @createDate: 2020/2/15
* @version: 1.0
*/
@Configuration
@EnableAuthorizationServer
public class AuthorServerConfig extends AuthorizationServerConfigurerAdapter
{
//一開始會有AuthenticationManager 無法注入,解決辦法就是繼承WebSecurityConfigurerAdapter
//重寫authenticationManager
@Autowired
AuthenticationManager authenticationManager;
@Autowired
RedisConnectionFactory redisConnectionFactory;
@Autowired
UserDetailsService userDetailsService;
@Bean
PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
{
clients.inMemory()
.withClient("password") //認證模式是password
.authorizedGrantTypes("password", "refresh_token") //授權模式
.accessTokenValiditySeconds(1800)//保留時間
.resourceIds("rid")//資源id
.scopes("all")
.secret("$2a$10$3gmKuxpj.noBDIGq31Joa..mmQA/gM9ZztEdk8T9YzUrK9ojqKx1i");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory)) //把token傳到redis裏
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception
{
security.allowFormAuthenticationForClients();
}
}
配置資源服務
package com.example.oauth.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
/**
* @description:
* 資源服務器
* @author: Leo
* @createDate: 2020/2/15
* @version: 1.0
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter
{
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception
{
resources.resourceId("rid").stateless(true);//指定資源id,要和授權裏面資源id保持一致
//stateless 資源是基於令牌認證
}
@Override
public void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests().antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasAnyRole("user","admin")
.anyRequest().authenticated();
}
}
安全配置
package com.example.oauth.config;
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.core.userdetails.UserDetailsService;
/**
* @description:
* @author: Leo
* @createDate: 2020/2/15
* @version: 1.0
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception
{
return super.authenticationManager();
}
@Bean
@Override
protected UserDetailsService userDetailsService()
{
return super.userDetailsService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
.withUser("leo").password("$2a$10$3gmKuxpj.noBDIGq31Joa..mmQA/gM9ZztEdk8T9YzUrK9ojqKx1i")
.roles("admin")
.and()
.withUser("jcl").password("$2a$10$3gmKuxpj.noBDIGq31Joa..mmQA/gM9ZztEdk8T9YzUrK9ojqKx1i")
.roles("user");
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.antMatcher("/oauth/**").authorizeRequests()
.antMatchers("/oauth/**").permitAll()
.and().csrf().disable();
}
}
控制層測試
package com.example.oauth.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @author: Leo
* @createDate: 2020/2/15
* @version: 1.0
*/
@RestController
public class HelloController
{
@GetMapping("/admin/hello")
public String admin(){
return "admin";
}
@GetMapping("/user/hello")
public String user(){
return "user";
}
@GetMapping("/hello")
public String hello(){
return "hello";
}
}
發送post請求
返回:
access_token:用來請求接口的token
refresh_token:用來獲取新的token
token過期
當token時間超過了自己設定的存活時間,就會過期,我這邊設置了30分鐘
所以需要重新獲取token
可以看到,token時間被重新刷新了,訪問,正常!