欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 前端技术 > javascript >内容正文

javascript

springsecruity整合oauth2 详解(一) -凯发k8官方网

发布时间:2025/1/21 javascript 17 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 springsecruity整合oauth2 详解(一) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

文章目录

    • 一、创建项目添加依赖
    • 二、添加application.properties
    • 三、配置授权服务器
    • 四、配置资源服务器
    • 五、配置spring security
    • 五、测试验证

前言:上一章oauth2 详解介绍了oauth2是干什么的,使用场景,运行原理以及授权模式。
这一章我们主要以密码模式举例
密码模式:
第一步:用户访问用页面时,输入第三方认证所需要的信息(qq/微信账号密码)
第二步:应用页面那种这个信息去认证服务器授权
第三步:认证服务器授权通过,拿到token,访问真正的资源页面

一、创建项目添加依赖

创建springboot web项目 添加依赖

4.0.0com.slspring-boot-security-oauth21.0-snapshot1.8org.springframework.bootspring-boot-starter-parent2.1.6.release org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-starter-securityorg.springframework.bootspring-boot-starter-data-redisio.lettucelettuce-coreorg.springframework.security.oauthspring-security-oauth22.3.3.releaseredis.clientsjedisorg.springframework.bootspring-boot-maven-plugin

在依赖中添加了redis,因为redis有过期功能,很适合令牌存储。

二、添加application.properties

spring.redis.database=0 spring.redis.host=localhost spring.redis.port=6379 spring.redis.jedis.pool.max-active=8 spring.redis.jedis.pool.max-idle=8 spring.redis.jedis.pool.max-wait=-1ms spring.redis.jedis.pool.min-idle=0

三、配置授权服务器

授权范围器和资源服务器可以是同一台服务器,也可是不同服务器,这里是同一台服务器

/*** @author shuliangzhao* @title: authorizationserverconfig* @projectname spring-boot-learn* @description: todo* @date 2019/9/4 20:24*/ @configuration @enableauthorizationserver public class authorizationserverconfig extends authorizationserverconfigureradapter {@autowiredprivate authenticationmanager authenticationmanager;@autowiredprivate redisconnectionfactory redisconnectionfactory;@autowiredprivate userdetailsservice userdetailsservice;@beanpublic passwordencoder passwordencoder() {return new bcryptpasswordencoder();}@overridepublic void configure(clientdetailsserviceconfigurer clients) throws exception {clients.inmemory().withclient("password").authorizedgranttypes("password","refresh_token")//表示授权模式支持password和refresh_token.accesstokenvalidityseconds(1800).resourceids("rid")//配置资源id.scopes("all").secret("$2a$10$yjmpy5kumnk2yrgt5zead.eapha7.wyxglpb9pzmjbzdi1spupgty");//配置加密后的密码}@overridepublic void configure(authorizationserverendpointsconfigurer endpoints) throws exception {endpoints.tokenstore(new redistokenstore(redisconnectionfactory)).authenticationmanager(authenticationmanager).allowedtokenendpointrequestmethods(httpmethod.get, httpmethod.post).userdetailsservice(userdetailsservice);}@overridepublic void configure(authorizationserversecurityconfigurer security) throws exception {//表示支持client_id和client_secretsecurity.allowformauthenticationforclients();}public static void main(string[] args) {string encode = new bcryptpasswordencoder().encode("123");system.out.println(encode);}}

自定义类authorizationserverconfig 继承authorizationserverconfigureradapter ,完成对授权服务器的配置,然后通过直接@enableauthorizationserver开发授权服务器。

四、配置资源服务器

资源服务器

/*** @author shuliangzhao* @title: resourceserver* @projectname spring-boot-learn* @description: todo* @date 2019/9/4 20:37*/ @configuration @enableresourceserver public class resourceserver extends resourceserverconfigureradapter{@overridepublic void configure(resourceserversecurityconfigurer resources) throws exception {//配置资源id,这里的资源id和授权服务器的资源id一致。资源仅基于令牌认证resources.resourceid("rid").stateless(true);}@overridepublic void configure(httpsecurity http) throws exception {http.authorizerequests().antmatchers("/admin/**").hasrole("admin").antmatchers("/user/**").hasrole("user").anyrequest().authenticated();}}

自定义类resourceserver 继承resourceserverconfigureradapter,添加注解enableresourceserver开启资源服务器

五、配置spring security

/*** @author shuliangzhao* @title: websecurityconfig* @projectname spring-boot-learn* @description: todo* @date 2019/9/4 20:41*/ @configuration @enablewebsecurity public class websecurityconfig extends websecurityconfigureradapter {@bean@overridepublic authenticationmanager authenticationmanagerbean() throws exception {return super.authenticationmanagerbean();}@beanprotected userdetailsservice userdetailsservice() {return super.userdetailsservice();}@overrideprotected void configure(authenticationmanagerbuilder auth) throws exception {auth.inmemoryauthentication().withuser("admin").password("$2a$10$yjmpy5kumnk2yrgt5zead.eapha7.wyxglpb9pzmjbzdi1spupgty").roles("admin").and().withuser("zhao").password("$2a$10$yjmpy5kumnk2yrgt5zead.eapha7.wyxglpb9pzmjbzdi1spupgty").roles("user");}@overrideprotected void configure(httpsecurity http) throws exception {http.antmatcher("/oauth/**").authorizerequests().antmatchers("/oauth/**").permitall().and().csrf().disable();} }

敲黑板:spring security配置和资源服务器配置中,一共涉及了两个httpsecurity,其中spring security中的配置优先级高于资源服务器的配置,即请求地址先经过springsecurity的httsecurity

五、测试验证

@restcontroller public class oauth2controller {@getmapping("/admin/hello")public string admin() {return "hello admin";}@getmapping("/user/hello")public string user() {return "hello user";}@getmapping("/hello")public string hello() {return "hello";} }

所有配置完成后我们启动项目,授权发送一个post请求获取token
http://localhost:8080/oauth/token?username=zhao&password=123&grant_type=password&client_id=password&scope=all&client_secret=123
请求地址中参数包括用户名,密码,授权模式,客户端id,scope以及客户端密码。返回信息:

{"access_token": "624df6db-637c-4094-a4ac-f34b30c8e170","token_type": "bearer","refresh_token": "df8093e4-0c20-4157-8f1c-f0d071c75dff","expires_in": 1668,"scope": "all" }

返回结果又access_token,token_type,refresh_token,expires_in以及scope,其中access_token是获取其它资源的令牌。refresh_tokn是刷新令牌,expires_in是过期时间。

刷新token的链接:
http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=df8093e4-0c20-4157-8f1c-f0d071c75dff&client_id=password&client_secret=123
返回结果:

{"access_token": "9ff75b32-ece9-479f-bfea-c8deb42c172f","token_type": "bearer","refresh_token": "df8093e4-0c20-4157-8f1c-f0d071c75dff","expires_in": 1799,"scope": "all" }

获取访问资源
http://localhost:8080/user/hello?access_token=9ff75b32-ece9-479f-bfea-c8deb42c172f
返回结果
hello user

总结

以上是凯发k8官方网为你收集整理的springsecruity整合oauth2 详解(一)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

  • 上一篇:
  • 下一篇:
网站地图