当前位置: 首页>編程日記>正文

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)

前言

    要解决的问题:不暴露客户密码的情况下授权三方服务访问客户资源

    角色:资源拥有者,客户端应用(三方服务),授权服务器,资源服务器

    模式:授权码模式:需要客户授权得到授权码后再次通过三方服务的密码取得token,双重校验,最安全,最复杂

               简易模式:无需授权码对用户暴露返回的Token,不安全

               密码模式:客户端应用需要资源拥有者密码。全链路可信情况下使用

               客户端模式:无需资源拥有者密码,只需要客户端应用密码进行校验,服务器对服务器使用

       本试验主要演示注册码模式,分为授权服务器和资源服务器俩个应用,后续会持续扩展为单个授权服务器和多个资源服务器。

试验步骤

按照以下截图创建授权服务器,授权服务器包结构如下


1 使用pom文件导入相应依赖,主要导入了以下依赖包

1)SpringBoot的security和web,

2)SpringSecurity的OAuth2

pom文件如下

<?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><groupId>io.spring2go</groupId><artifactId>authcode-server</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>authcode-server</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.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></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><!-- for OAuth 2.0 --><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></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>

2 修改application.properties设置用户登录密码

# Spring Security Setting
security.user.name=bobo
security.user.password=xyz

3 制作SpringBoot的启动文件

package com.test.authcodeserver;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class AuthCodeServerApplication {public static void main(String[] args) {SpringApplication.run(AuthCodeServerApplication.class, args);}
}
4 设置授权服务代码

package com.test.authcodeserver.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
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.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;@Configuration
@EnableAuthorizationServer
public class AuthCodeServerConfig extends AuthorizationServerConfigurerAdapter {


    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");}@Override
    public void configure(ClientDetailsServiceConfigurer clients)throws Exception {//JdbcClientDetailsService可以动态管理数据库中客户端数据
        //http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo
        clients.inMemory().withClient("testclientid")//clientId:(必须的)用来标识客户的Id。
                .secret("1234")//secret:(需要值得信任的客户端)客户端安全码,如果有的话。
                .redirectUris("http://localhost:9001/authCodeCallback")//客户端应用负责获取授权码的endpoint
                .authorizedGrantTypes("authorization_code")// 授权码模式
                .scopes("read_userinfo", "read_contacts");//scope:用来限制客户端的访问范围,如果为空(默认)的话,那么客户端拥有全部的访问范围。
    }}

5 启动SpringBoot服务

6 客户端服务访问授权服务器,铜鼓访问如下url取得授权码

http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo

访问完成后会redirect回客户端服务器并将授权码作为参数传回,其中localhost:9001即为客户端应用


7 客户端使用返回的授权码获取访问令牌



发送请求参数如下

url:http://localhost:8080/oauth/token

code=ifz2BV&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A9001%2FauthCodeCallback&scope=read_userinfo

得到的令牌数据

{
access_token"554338cd-cab0-4ba0-b5bf-3ebd55db3196"
token_type"bearer"
expires_in43199
scope"read_userinfo"

}

以上授权服务器就简单完成了,下面将制作资源服务器


--------------------------------------------------------------------------------------------------


资源服务器

0 资源服务器的包结构


1 资源服务器配置,使用RemoteTokenServices调取认证服务器的认证方法来对Token进行认证

package com.test.resourceserver.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
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;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.web.AuthenticationEntryPoint;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;//资源服务配置
@Configuration
@EnableResourceServer
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {@Primary
    @Bean
    public RemoteTokenServices tokenServices() {final RemoteTokenServices tokenService = new RemoteTokenServices();tokenService.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");tokenService.setClientId("testclientid");tokenService.setClientSecret("1234");return tokenService;}@Override
    public void configure(HttpSecurity http) throws Exception {//        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
//                .and()
//                .authorizeRequests()
//                .anyRequest()
//                .authenticated()
//                .and()
//                .requestMatchers()
//                .antMatchers("/api/**");
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().authorizeRequests().anyRequest().permitAll();}
}

2 提供对外的API接口

package com.test.resourceserver.api;import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class UserController {// 资源API
    @RequestMapping("/api/userinfo")public ResponseEntity<UserInfo> getUserInfo() {String  user  = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();String email = user+ "@test.com";UserInfo userInfo = new UserInfo();userInfo.setName(user);userInfo.setEmail(email);return ResponseEntity.ok(userInfo);}}
调用getUserInfo

http://localhost:8004/api/userinfo 

authorization: Bearer 638aa01c-4ccd-4873-ab86-d46f22aea091


调用后返回资源服务器的结果


至此一个资源服务器和认证服务器分离的资源调用就结束了。



https://www.fengoutiyan.com/post/15436.html

相关文章:

  • 一台服务器一般装几个服务
  • 服务器怎么加入域
  • 服务器域要和用户域分离吗
  • oauth2资源服务器校验token
  • 服务器已取消对客户端的认证
  • 服务器加入域后服务不能用
  • oauth2认证流程
  • oauth2 jwt
  • 鏡像模式如何設置在哪,圖片鏡像操作
  • 什么軟件可以把圖片鏡像翻轉,C#圖片處理 解決左右鏡像相反(旋轉圖片)
  • 手機照片鏡像翻轉,C#圖像鏡像
  • 視頻鏡像翻轉軟件,python圖片鏡像翻轉_python中鏡像實現方法
  • 什么軟件可以把圖片鏡像翻轉,利用PS實現圖片的鏡像處理
  • 照片鏡像翻轉app,java實現圖片鏡像翻轉
  • 什么軟件可以把圖片鏡像翻轉,python圖片鏡像翻轉_python圖像處理之鏡像實現方法
  • matlab下載,matlab如何鏡像處理圖片,matlab實現圖像鏡像
  • 圖片鏡像翻轉,MATLAB:鏡像圖片
  • 鏡像翻轉圖片的軟件,圖像處理:實現圖片鏡像(基于python)
  • canvas可畫,JavaScript - canvas - 鏡像圖片
  • 圖片鏡像翻轉,UGUI優化:使用鏡像圖片
  • Codeforces,CodeForces 1253C
  • MySQL下載安裝,Mysql ERROR: 1253 解決方法
  • 勝利大逃亡英雄逃亡方案,HDU - 1253 勝利大逃亡 BFS
  • 大一c語言期末考試試題及答案匯總,電大計算機C語言1253,1253《C語言程序設計》電大期末精彩試題及其問題詳解
  • lu求解線性方程組,P1253 [yLOI2018] 扶蘇的問題 (線段樹)
  • c語言程序設計基礎題庫,1253號C語言程序設計試題,2016年1月試卷號1253C語言程序設計A.pdf
  • 信奧賽一本通官網,【信奧賽一本通】1253:抓住那頭牛(詳細代碼)
  • c語言程序設計1253,1253c語言程序設計a(2010年1月)
  • 勝利大逃亡英雄逃亡方案,BFS——1253 勝利大逃亡
  • 直流電壓測量模塊,IM1253B交直流電能計量模塊(艾銳達光電)
  • c語言程序設計第三版課后答案,【渝粵題庫】國家開放大學2021春1253C語言程序設計答案
  • 18轉換為二進制,1253. 將數字轉換為16進制
  • light-emitting diode,LightOJ-1253 Misere Nim
  • masterroyale魔改版,1253 Dungeon Master
  • codeformer官網中文版,codeforces.1253 B
  • c語言程序設計考研真題及答案,2020C語言程序設計1253,1253計算機科學與技術專業C語言程序設計A科目2020年09月國家開 放大學(中央廣播電視大學)
  • c語言程序設計基礎題庫,1253本科2016c語言程序設計試題,1253電大《C語言程序設計A》試題和答案200901
  • 肇事逃逸車輛無法聯系到車主怎么辦,1253尋找肇事司機