SpringSecurity(14)——OAuth2简化模式

工作流程

在这里插入图片描述

基本使用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.3.12.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.3.12.RELEASE</version>
</dependency>
@Configuration
public class MyOAuth2Config {

    /**
    * 加密方式
    */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
  1. 创建安全配置类:指定认证用户的用户名和密码,用户和密码是资源的所有者,
  2. 创建认证服务器:这个客户端id和密码跟上面的用户名和密码是不一样的,客户端id和密码是应用系统的标识,每个应用系统对应一个客户端id和密码
/**
 * 安全配置类
 */
@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("123456"))
                .authorities("admin_roles");
    }
}
/**
 * 认证服务器
 */
@Configuration
@EnableAuthorizationServer //开启认证服务器
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 配置被允许访问此认证服务器的客户端详细信息
     * 1.内存管理
     * 2.数据库管理方式
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //客户端名称
                .withClient("test-pc")
                //客户端密码
                .secret(passwordEncoder.encode("123456"))
                //资源id,商品资源
                .resourceIds("oauth2-server")
                /**
                 * 授权类型,可同时支持多种授权类型
                 * authorization_code:授权码模式
                 * password:密码模式
                 * implicit:简化模式
                 * client_credentials:客户端模式
                 * refresh_token:更新令牌
                 */
                .authorizedGrantTypes("implicit","refresh_token")
                //授权范围标识,哪部分资源可访问(all是标识,不是代表所有)
                //比如指定微服务名称,则只可以访问指定的微服务
                .scopes("all")
                //false跳转到授权页面手动点击授权,true不用手动授权,直接响应授权码
                .autoApprove(false)
                //客户端回调地址,一定要和申请授权码时用的redirect_uri一致
                //当获取授权码后,认证服务器会重定向到指定的这个URL,并且带着一个授权码code响应
                .redirectUris("http://www.baidu.com/");
    }
}

获取Access Token

接口获取

Authorization Request

  • response_type:必须的。值必须是"token"。
  • client_id:必须的。
  • redirect_uri:可选的。
  • scope:可选的。

例如:

  1. http://localhost:8080/oauth/authorize?response_type=token&client_id=banana&redirect_uri=http://baidu.com
  2. http://localhost:8080/oauth/authorize?response_type=token&client_id=client1

浏览器获取

  1. 输入访问地址:http://localhost:8080/oauth/authorize?client_id=test-pc&response_type=token
  2. 当请求到达认证服务器的AuthorizationEndpoint后,它会要求资源所有者做身份验证.

image.png

  1. 点击登录后,会跳转到指定的redirect_uri,回调路径会携带者令牌access_token、expires_in、scope等

image.png

### 实现Spring Security OAuth2密码授权模式整合 为了在Spring Security中实现OAuth2密码授权模式的整合,需遵循一系列配置和编码实践。具体来说,在应用程序中引入必要的依赖项之后,还需设置认证服务器以及客户端的相关属性。 #### 添加Maven依赖 首先,在`pom.xml`文件中加入支持OAuth2自动配置的支持: ```xml <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.3.RELEASE</version> </dependency> ``` 此操作确保了应用能够利用Spring Boot Starter简化OAuth2组件的初始化过程[^3]。 #### 配置认证服务器 创建一个类来定义认证服务器的行为,并通过注解指定其作为资源服务端的角色。对于密码授权模式而言,重要的是要允许特定类型的令牌授予请求——即password类型。这通常涉及到重写默认的安全配置并注册自定义化的TokenEndpointAuthenticationFilter过滤器以处理来自用户的凭证提交。 ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("my-trusted-client") .authorizedGrantTypes("password", "authorization_code", "refresh_token") .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT") .scopes("read", "write", "trust") .resourceIds("oauth2-resource") .secret("{noop}secret"); } @Bean @Primary public DefaultTokenServices tokenServices() { final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setSupportRefreshToken(true); return defaultTokenServices; } } ``` 上述代码片段展示了如何声明内存中的客户端详情服务实例及其权限范围;同时也启用了刷新令牌的功能以便于长期访问控制[^1]。 #### 客户端发起token请求 当一切准备就绪后,客户端可以通过POST方法向`/auth/oauth/token`发送HTTP请求获取access token。此时应携带基本身份验证头信息(Base64编码后的client_id:client_secret),并将用户名、密码以及其他必要参数放在查询字符串或表单数据内传递给服务器。 ```javascript return request({ url: '/auth/oauth/token', headers: { 'isToken': false, 'Authorization': 'Basic YWRtaW46YWRtaW4=' // Base64 encoded admin:admin }, method: 'post', params: { username: 'yourUsernameHere', password: 'yourPasswordHere', grant_type: 'password', scope: 'read write' } }); ``` 这段JavaScript AJAX调用模拟了一个典型的场景,其中包含了必需的身份验证头部字段与body内的参数列表[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值