spring boot 2.0 整合 oauth2 authorization code授權碼模式
oauth2 authorization code 大致流程
- 使用者開啟客戶端後,客戶端要求使用者給予授權。
- 使用者同意給予客戶端授權。
- 客戶端使用授權得到的code,向認證伺服器申請token令牌。
- 認證伺服器對客戶端進行認證以後,確認無誤,同意發放令牌。
- 客戶端請求資源時攜帶token令牌,向資源伺服器申請獲取資源。
- 資源伺服器確認令牌無誤,同意向客戶端開放資源。
security oauth2 整合的核心配置類
- 授權認證服務配置 AuthorizationServerConfiguration
- security 配置 SecurityConfiguration
工程結構目錄
pom.xml
<artifactId>security_oauth2_authorization</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>security_oauth2_authorization</name>
<description>oauth2 authorization_code 授權模式</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<security-jwt.version>1.0.9.RELEASE</security-jwt.version>
<jjwt.version>0.9.0</jjwt.version>
<spring-cloud.version>Finchley.RC2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>${security-jwt.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
授權認證服務配置類 AuthorizationServerConfiguration
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private MyUserDetailsService userDetailsService;
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String secret = passwordEncoder.encode("secret");
clients.inMemory() // 使用in-memory儲存
.withClient("client") // client_id
.secret(secret) // client_secret
//.autoApprove(true) //如果為true 則不會跳轉到授權頁面,而是直接同意授權返回code
.authorizedGrantTypes("authorization_code","refresh_token") // 該client允許的授權型別
.scopes("app"); // 允許的授權範圍
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService)
.accessTokenConverter(accessTokenConverter())
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); //支援GET POST 請求獲取token;
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter() {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
String userName = authentication.getUserAuthentication().getName();
final Map<String, Object> additionalInformation = new HashMap<String, Object>();
additionalInformation.put("user_name", userName);
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
OAuth2AccessToken token = super.enhance(accessToken, authentication);
return token;
}
};
//converter.setSigningKey("bcrypt");
KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource("kevin_key.jks"), "123456".toCharArray())
.getKeyPair("kevin_key");
converter.setKeyPair(keyPair);
return converter;
}
}
web 安全配置 WebSecurityConfig
@Order(10)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsFitService;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/","/oauth/**","/login","/health", "/css/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsFitService).passwordEncoder(passwordEncoder());
auth.parentAuthenticationManager(authenticationManagerBean());
}
@Bean
public PasswordEncoder passwordEncoder(){
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
url 註冊配置 MvcConfig
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login"); //自定義的登陸頁面
registry.addViewController("/oauth/confirm_access").setViewName("oauth_approval"); //自定義的授權頁面
}
}
# security 登陸認證 MyUserDetailsService
@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
if ("admin".equalsIgnoreCase(name)) {
User user = mockUser();
return user;
}
return null;
}
private User mockUser() {
Collection<GrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority("admin"));
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String pwd = passwordEncoder.encode("123456");
User user = new User("admin",pwd,authorities);
return user;
}
}
自定義登陸頁面 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陸</title>
<link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="portlet-body">
<form class="form-horizontal" action="login" role="form" method="post">
<div class="form-group">
<label for="username" class="col-md-2 control-label">username</label>
<div class="col-md-6">
<input type="text" class="form-control" id="username" name="username" placeholder="username"> </div>
</div>
<div class="form-group">
<label for="password" class="col-md-2 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" id="password" name="password" placeholder="password"> </div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn blue">登陸</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.1.1/js/bootstrap.min.js" crossorigin="anonymous"></script>
</body>
</html>
自定義授權頁面 oauth_approval.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>授權</title>
<link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>你是否授權client_id=client訪問你的受保護資源?</h2>
<div style="height: 20px;"></div>
<form id="confirmationForm" name="confirmationForm"
action="../oauth/authorize" method="post">
<input name="user_oauth_approval" value="true" type="hidden"/>
<button class="btn btn-primary" type="submit">Approve</button>
</form>
<div style="height: 20px;"></div>
<form id="denyForm" name="confirmationForm"
action="../oauth/authorize" method="post">
<input name="user_oauth_approval" value="false" type="hidden"/>
<button class="btn btn-primary" type="submit">Deny</button>
</form>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.1.1/js/bootstrap.min.js" crossorigin="anonymous"></script>
</body>
</html>
application.yml
server:
port: 18084
spring:
application:
name: oauth2-server # 應用名稱
thymeleaf:
prefix: classpath:/templates/
logging:
level:
org.springframework.security: DEBUG
1. 訪問oauth2 服務
client_id:第三方應用在授權伺服器註冊的 Id
response_type:固定值 code。
redirect_uri:授權伺服器授權重定向哪兒的 URL。
scope:許可權
state:隨機字串,可以省略
如果未登陸則出現登入頁面,輸入使用者名稱:admin 密碼:123456 登陸系統
2. 成功登陸後自動跳轉到授權頁面
- 點選“approve” 同意授權獲取code返回:https://www.baidu.com/?code=1LerDZ&state=123
- 點選“deny” 拒絕授權 返回:https://www.baidu.com/?error=access_denied&error_description=User%20denied%20access&state=123
3. 攜帶授權之後返回的code 獲取token
http://localhost:18084/oauth/token?client_id=client&grant_type=authorization_code&redirect_uri=http://baidu.com&code=bzxoHn
如果沒有登陸會出現登陸頁面 輸入:賬號 client 密碼 secret 登陸
這裡的賬號和密碼 是我們註冊的 client_id 和 client_secret
成功登陸後獲取token
4.攜帶toekn 訪問資源
demo地址:
相關文章
- IdentityServer4 (3) 授權碼模式(Authorization Code)IDEServer模式
- spring boot 2.0 整合 security oauth2 password 模式和credentials 模式Spring BootOAuth模式
- 九、Spring Boot整合Spring Security之授權概述Spring Boot
- oauth2.0授權碼模式OAuth模式
- IdentityServer4之Authorization Code(授權碼)相對更安全IDEServer
- OAuth 2.0(Open Authorization 2.0)授權框架入門介紹OAuth框架
- Spring Authorization Server 實現授權中心SpringServer
- 十、Spring Boot整合Spring Security之HTTP請求授權Spring BootHTTP
- Oauth2認證模式之授權碼模式實現OAuth模式
- Shiro(授權Authorization)
- Spring Boot 2.0(八):Spring Boot 整合 MemcachedSpring Boot
- OAuth2.0授權碼模式詳解OAuth模式
- Spring Authorization Server授權伺服器入門SpringServer伺服器
- Spring Boot 整合 Shiro實現認證及授權管理Spring Boot
- Spring Security如何優雅的增加OAuth2協議授權模式SpringOAuth協議模式
- Spring Boot Security OAuth2 實現支援JWT令牌的授權伺服器Spring BootOAuthJWT伺服器
- OAuth2.0協議入門(一):OAuth2.0協議的基本概念以及使用授權碼模式(authorization code)實現百度賬號登入OAuth協議模式
- OAuth2密碼模式已死,最先進的Spring Cloud認證授權方案在這裡OAuth密碼模式SpringCloud
- 授權(Authorization)和認證(Authentication)
- OAuth 2.0 授權碼認證OAuth
- OAuth 2.0 授權碼請求OAuth
- springcloud Oauth2授權,四種授權型別SpringGCCloudOAuth型別
- OAuth2.0的四種授權模式OAuth模式
- OAuth2.0安全設計之Authorization CodeOAuth
- 理解ASP.NET Core - 授權(Authorization)ASP.NET
- Spring Boot:整合Shiro許可權框架Spring Boot框架
- Spring Security OAuth2.0認證授權四:分散式系統認證授權SpringOAuth分散式
- 搞定了!OAuth2使用驗證碼進行授權OAuth
- 從零開始學Spring Boot系列-整合Spring Security實現使用者認證與授權Spring Boot
- Spring Boot Security 整合 OAuth2 設計安全API介面服務Spring BootOAuthAPI
- Spring Boot整合Redis叢集(Cluster模式)Spring BootRedis模式
- Spring Boot系列(三):Spring Boot整合Mybatis原始碼解析Spring BootMyBatis原始碼
- Spring Security原始碼分析十一:Spring Security OAuth2整合JWTSpring原始碼OAuthJWT
- Spring Boot 2.0(二):Spring Boot 2.0嚐鮮-動態 BannerSpring Boot
- IdentityServer4系列 | 授權碼模式IDEServer模式
- shiro入門學習--授權(Authorization)|築基初期
- Spring Security OAuth2.0認證授權三:使用JWT令牌SpringOAuthJWT
- Spring Security 實戰乾貨:客戶端OAuth2授權請求的Spring客戶端OAuth