搭建spring security oauth2认证授权服务器

这篇具有很好参考价值的文章主要介绍了搭建spring security oauth2认证授权服务器。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

下面是在spring security项目的基础上搭建spring security oauth2认证授权服务器

1、添加依赖

spring security oauth2认证授权服务器主要需要以下依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- for OAuth 2.0 -->
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>{oauth2_version}</version>
</dependency>

Spring Security对OAuth2默认可访问端点

​/oauth/authorize​ ​​:申请授权码code,涉及类​ ​AuthorizationEndpoint​ ​
​/oauth/token​ ​​:获取令牌token,涉及类​ ​TokenEndpoint​ ​

​ ​/oauth/check_token​ ​​:用于资源服务器请求端点来检查令牌是否有效,涉及类​ ​CheckTokenEndpoint​ ​

​ ​/oauth/confirm_access​ ​​:用于确认授权提交,涉及类​ ​WhitelabelApprovalEndpoint​ ​

​ ​/oauth/error​ ​​:授权错误信息,涉及​ ​WhitelabelErrorEndpoint​ ​

​ ​/oauth/token_key​ ​​:提供公有密匙的端点,使用JWT令牌时会使用,涉及类​ ​TokenKeyEndpoint​

2、创建认证授权配置类

认证授权服务器最重要的就是认证授权配置类的配置

1、创建 ​一个自定义 ​类继承​ ​AuthorizationServerConfigurerAdapter​ ​
2、在​ ​自定义 ​类上添加注解​@Configuration​和​@EnableAuthorizationServer​注解

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationManager authenticationManager;


    /**
     * 密码模式需要注入authenticationManager
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                //让/oauth/token支持client_id以及client_secret作登录认证
                .allowFormAuthenticationForClients();
    }

    /**
     * 客户端信息配置
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //客户端ID
                .withClient("admin")
                //客户端密码
                .secret(passwordEncoder.encode("123123"))
                //配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                //配置重定向的跳转,用于授权成功之后的跳转
                .redirectUris("http://www.baidu.com")
                //授权范围标识,哪部分资源可访问(all是标识,不是代表所有)
                .scopes("all")
                //授权模式, 可同时支持多种授权类型
                .authorizedGrantTypes("authorization_code", "password", "implicit","client_credentials","refresh_token")
                //true为自动批准,不需要用户手动点击授权,直接返回授权码
                .autoApprove(true);
    }




    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder() ;
    }



}

3、创建安全配置类

1、创建 ​一个自定义 ​类继承​ ​WebSecurityConfigurerAdapter​ ​
2、在​ ​自定义 ​类上添加注解​@Configuration​和​@EnableWebSecurity​注解

/**
 * 配置Web应用程序的安全性,包括定义哪些URL需要被保护(即需要进行身份验证),以及如何进行身份验证等
 */
@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //创建一个登录用户
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(passwordEncoder.encode("123123"))
                .authorities("admin_role");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭CSRF
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/auth/**", "/login/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }



    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        // 采用密码授权模式需要显式配置AuthenticationManager
        return super.authenticationManagerBean();
    }

}


4、获取授权码路径及参数

获取授权码的请求url:/oauth/authorize

参数列表如下

client_id:客户端准入标识。

response_type:授权码模式固定为code。

scope:客户端权限。

grant_type:授权类型,填写authorization_code,表示授权码模式

code:授权码,就是刚刚获取的授权码,注意:授权码只使用一次就无效了,需要重新申请。

redirect_uri:跳转uri,当授权码申请成功后会跳转到此地址,并在后边带上code参数

1、使用以下地址申请授权码
http://localhost:8080/oauth/authorize?client_id=test&response_type=code&grant_type=authorization_code&scop=all&redirect_uri=http://www.baidu.com

2、访问后,会让我们进行登录,登录成功之后就会跳转到我们的redirect_uri地址,并携带上了授权码

如下:fJf571就是我们的授权码

https://www.baidu.com/?code=fJf571

3、获取授权码之后,客户端就可以拿着授权码向授权服务器索要访问access_token

获取token的地址为:/oauth/token

参数列表如下:

client_id:客户端准入标识。
client_secret:客户端秘钥。
grant_type:授权类型,填写authorization_code,表示授权码模式
code:授权码,就是刚刚获取的授权码,注意:授权码只使用一次就无效了,需要重新申请。
redirect_uri:申请授权码时的跳转url,一定和申请授权码时用的redirect_uri一致
scope: 权限

postman测试

在authorization里添加一个basic auth,username为client_id,password为secret

搭建spring security oauth2认证授权服务器,Spring Security,spring,java,spring boot,spring security,oauth2
添加好认证信息之后,就可以请求接口了,下面就是授权模式下的获取token
搭建spring security oauth2认证授权服务器,Spring Security,spring,java,spring boot,spring security,oauth2
密码模式

使用密码模式,主要是要注入authenticationManagerBean类

(1)资源拥有者将用户名、密码发送给客户端

(2)客户端拿着资源拥有者的用户名、密码向授权服务器请求令牌(access_token),请求如下:

使用密码模式,我只需要请求获取token的url:/oauth/token

参数列表如下:

参数 说明
client_id 客户端ID
client_secret 客户端秘钥。
grant_type 授权类型,填写password表示密码模式
username 资源拥有者用户名。
password 资源拥有者密码
scope 权限

搭建spring security oauth2认证授权服务器,Spring Security,spring,java,spring boot,spring security,oauth2文章来源地址https://www.toymoban.com/news/detail-810959.html

到了这里,关于搭建spring security oauth2认证授权服务器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Security Oauth2.1 最新版 1.1.0 整合 (基于 springboot 3.1.0)gateway 完成授权认证

    目录 背景 demo地址 版本 Spring Boot 3.1 Spring Authorization Server 1.1.0 基础 spring security OAuth2 模块构成 授权方式 认证方式 集成过程 官方demo 代码集成 依赖 授权服务AuthorizationServerConfig配置 重要组件 测试 查看授权服务配置 访问授权服务 授权 回调 获取 access_token 获取用户信息 个性

    2024年02月11日
    浏览(40)
  • OAuth2.0 实践 Spring Authorization Server 搭建授权服务器 + Resource + Client

    title: OAuth2.0 实践 Spring Authorization Server 搭建授权服务器 + Resource + Client date: 2023-03-27 01:41:26 tags: OAuth2.0 Spring Authorization Server categories: 开发实践 cover: https://cover.png feature: false 目前 Spring 生态中的 OAuth2 授权服务器是 Spring Authorization Server ,原先的 Spring Security OAuth 已经停止更新

    2024年02月08日
    浏览(45)
  • Spring Security对接OIDC(OAuth2)外部认证

    前后端分离项目对接OIDC(OAuth2)外部认证,认证服务器可以使用Keycloak。 后端已有用户管理和权限管理,需要外部认证服务器的用户名和业务系统的用户名一致才可以登录。 后台基于Spring Boot 2.7 + Spring Security 流程: 前台浏览器跳转到  后台地址 + /login/oauth2/authorization/my-oid

    2024年02月21日
    浏览(33)
  • Spring Gateway+Security+OAuth2+RBAC 实现SSO统一认证平台

    背景:新项目准备用SSO来整合之前多个项目的登录和权限,同时引入网关来做后续的服务限流之类的操作,所以搭建了下面这个系统雏形。 : Spring Gateway, Spring Security, JWT, OAuth2, Nacos, Redis, Danymic datasource, Javax, thymeleaf 如果对上面这些技术感兴趣,可以继续往下阅读 如

    2024年02月13日
    浏览(38)
  • Spring Cloud Gateway 整合OAuth2.0 实现统一认证授权

    Spring Cloud Gateway 整合OAuth2.0 实现统一认证授权 GateWay——向其他服务传递参数数据 https://blog.csdn.net/qq_38322527/article/details/126530849 @EnableAuthorizationServer Oauth2ServerConfig 验证签名 网关服务需要RSA的公钥来验证签名是否合法,所以认证服务需要有个接口把公钥暴露出来 接下来搭建网

    2024年02月13日
    浏览(29)
  • Spring OAuth2 授权服务器配置详解

    首先要创建一个Spring Boot Servlet Web项目,这个不难就不赘述了。集成 Spring Authorization Server 需要引入: OAuth2.0 Client 客户端需要注册到授权服务器并持久化, Spring Authorization Server 提供了 JDBC 实现,参见 JdbcRegisteredClientRepository 。为了演示方便这里我采用了H2数据库,需要以下依

    2024年04月13日
    浏览(32)
  • Spring Authorization Server入门 (八) Spring Boot引入Security OAuth2 Client对接认证服务

    在之前的文章中实现了一个认证服务,并且添加了一些自定义的内容,现在暂时没想到认证服务的新内容,本篇文章就先写一下客户端对接的吧,水一篇。 当用户通过客户端去访问一个受限的资源时,客户端会检测是否有登录信息,没有登录信息会重定向至认证服务器去请求

    2024年02月21日
    浏览(38)
  • 【SpringBoot】自从集成spring-security-oauth2后,实现统一认证授权so easy!

    principal:能唯一标识用户身份的属性,一个用户可以有多个principal 如登录的唯一标识, 用户可以使用用户名或手机或邮箱进行登录 ,这些principal是让别人知道的 credential:凭证,用户才知道的,简单的说就是 密码 如:手机开锁,可以使用 屏幕密码 也可以使用 人脸识别 ,

    2023年04月24日
    浏览(66)
  • spring cloud、gradle、父子项目、微服务框架搭建---spring secuity oauth2、mysql 授权(九)

    https://preparedata.blog.csdn.net/article/details/120062997 新建两个服务 1.授权服务 端口号:11007 2.资源服务 端口号:11004 资源服务可以是订单服务、用户服务、商品服务等等 当然这两个服务也可以合并到一起, 依次顺序AuthorizationServerConfiguration、ResourceServerConfig、WebSecurityConfiguration;

    2024年02月10日
    浏览(29)
  • 【Oauth2.0 单点登录 + 第三方授权认证】用户认证、授权模式

    本文主要对 SpringSecurity Oauth 2.0 用户认证,授权码授权模式、密码授权模式,以及授权流程进行讲解 开发中,有些功能只有管理员才有,普通用户是没有的。即需要对用户的身份进行认证,是管理员还是普通用户。认证方式有两种: 身份认证: 用户在访问相应资源时对用户

    2023年04月08日
    浏览(48)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包