Spring Security OAuth2.0系列之密码模式

ps:OAuth2.0的授权模式可以分为:

  • 授权码模式(authorization code)
  • 简化模式(implicit)
  • 密码模式(resource owner password credentials)
  • 客户端模式(client credentials)

密码模式(resource owner password credentials):密码模式中,用户向客户端提供自己的用户名和密码,这通常用在用户对客户端高度信任的情况;

1.2 授权流程图

官网图片:

在这里插入图片描述

  • (A)用户访问客户端,提供URI连接包含用户名和密码信息给授权服务器
  • (B)授权服务器对客户端进行身份验证
  • (C)授权通过,返回acceptToken给客户端

从调接口方面,简单来说:

  • 第一步:直接传username,password获取token;

http://localhost:8080/oauth/token?password=123&grant_type=password&username=nicky&scope=all

  • 第二步:拿到acceptToken之后,就可以直接访问资源

http://localhost:8084/api/userinfo?access_token=${accept_token}

2、例子实践

2.1 实验环境准备

  • IntelliJ IDEA
  • Maven3.+版本 新建SpringBoot Initializer项目,

pom.xml 配置:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.allen</groupId>
    <artifactId>spring-oauth2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-oauth2</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.2 OAuth2.0角色

前面的学习,我们知道了OAuth2.0主要包括如下角色,下面通过代码例子加深对理论的理解

  • 资源所有者(Resource Owner)
  • 用户代理(User Agent)
  • 客户端(Client)
  • 授权服务器(Authorization Server)
  • 资源服务器(Resource Server)

生产环境、资源服务器和授权服务器一般是分开的,不过学习的可以放在一起

定义资源服务器,用注解@EnableResourceServer,主要作用是对不同URL的拦截和放行;

定义授权服务器,用注解@EnableAuthorizationServer;

2.3 OAuth2.0配置类

新建config包,

package com.allen.springoauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;


/**
 * <pre>
 *     OAuth2.0配置类
 * </pre>
 */
@Configuration
//开启授权服务
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    private static final String CLIENT_ID = "cms";
    private static final String SECRET_CHAR_SEQUENCE = "{noop}secret";
    private static final String SCOPE_READ = "read";
    private static final String SCOPE_WRITE = "write";
    private static final String TRUST = "trust";
    private static final String USER ="user";
    private static final String ALL = "all";
    private static final int ACCESS_TOKEN_VALIDITY_SECONDS = 2*60;
    private static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 2*60;
    // 密码模式授权模式
    private static final String GRANT_TYPE_PASSWORD = "password";
    //授权码模式
    private static final String AUTHORIZATION_CODE = "authorization_code";
    //refresh token模式
    private static final String REFRESH_TOKEN = "refresh_token";
    //简化授权模式
    private static final String IMPLICIT = "implicit";
    //指定哪些资源是需要授权验证的
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                // 使用内存存储
                .inMemory()
                //标记客户端id
                .withClient(CLIENT_ID)
                //客户端安全码
                .secret(SECRET_CHAR_SEQUENCE)
                //为true 直接自动授权成功返回code
                .autoApprove(true)
                .redirectUris("http://127.0.0.1:8084/cms/login") //重定向uri
                //允许授权范围
                .scopes(ALL)
                //token 时间秒
                .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
                //刷新token 时间 秒
                .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS)
                //允许授权类型
                .authorizedGrantTypes(GRANT_TYPE_PASSWORD );
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 使用内存保存生成的token
        endpoints.authenticationManager(authenticationManager).tokenStore(memoryTokenStore());
    }

    /**
     * 认证服务器的安全配置
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //.realm(RESOURCE_ID)
                // 开启/oauth/token_key验证端口认证权限访问
                .tokenKeyAccess("isAuthenticated()")
                //  开启/oauth/check_token验证端口认证权限访问
                .checkTokenAccess("isAuthenticated()")
                //允许表单认证
                .allowFormAuthenticationForClients();
    }

    @Bean
    public TokenStore memoryTokenStore() {
        // 最基本的InMemoryTokenStore生成token
        return new InMemoryTokenStore();
    }

}

2.4 Security配置类

为了测试,可以进行简单的SpringSecurity,

package com.allen.springoauth2.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * <pre>
 *  SpringSecurity配置类
 * </pre>
 */
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {    //auth.inMemoryAuthentication()
        auth.inMemoryAuthentication()
                .withUser("nicky")
                .password("{noop}123")
                .roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/asserts/**");
        web.ignoring().antMatchers("/favicon.ico");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http   // 配置登录页并允许访问
                //.formLogin().permitAll()
                // 配置Basic登录
                //.and().httpBasic()
                // 配置登出页面
                .logout().logoutUrl("/logout").logoutSuccessUrl("/")
                // 配置允许访问的链接
                .and().authorizeRequests().antMatchers("/oauth/**", "/login/**", "/logout/**","/api/**").permitAll()
                // 其余所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                // 关闭跨域保护;
                .and().csrf().disable();
    }

}

2.5 功能简单测试

接口测试,要用POST方式,在postman测试,grant_type参数传password:

接口地址:http://localhost:8080/oauth/token

Params参数:

 注意配置一下请求头的授权参数,username即client_id,password即client_secret:

 请求结果:

 新建controller类,

package com.allen.springoauth2.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * @author :jhys
 * @date :Created in 2021/9/6 22:14
 * @Description :
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class UserController {

    @GetMapping("/userinfo")
    public String getCurrentUser(Principal principal) {
        log.info("访问成功");
        return "Hello";
    }
}

拿到access_token直接去调业务接口, 访问成功!

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 好的,我可以为您提供关于Spring Security OAuth 2.0实现的中文回答。 Spring Security OAuth 2.0是Spring Security框架的一部分,它为应用程序提供了OAuth 2.0认证和授权的支持。OAuth 2.0是一种常用的授权协议,它允许用户授权第三方应用程序访问他们的受保护资源。Spring Security OAuth 2.0实现了OAuth 2.0协议中的授权服务器和资源服务器两个角色。 要使用Spring Security OAuth 2.0,您需要完成以下步骤: 1.添加Spring Security OAuth 2.0依赖项:在Maven或Gradle项目中,您需要添加Spring Security OAuth 2.0的依赖项。例如,在Maven项目中,您可以添加以下依赖项: ```xml <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.6.RELEASE</version> </dependency> ``` 2.配置OAuth 2.0客户端:您需要配置OAuth 2.0客户端,以便您的应用程序可以访问受保护的资源。这通常涉及到注册应用程序并获取客户端ID和客户端密钥。 3.配置授权服务器:您需要配置授权服务器,以便用户可以授权应用程序访问他们的受保护资源。授权服务器可以与您的应用程序集成,也可以作为单独的服务运行。 4.配置资源服务器:您需要配置资源服务器,以便它可以验证访问令牌并授予对受保护资源的访问权限。 5.保护受保护的资源:您需要配置Spring Security以保护受保护的资源,并确保只有经过身份验证和授权的用户可以访问它们。 以上是使用Spring Security OAuth 2.0实现OAuth 2.0认证和授权所需的主要步骤。如果您需要更详细的指导,请参考Spring Security OAuth 2.0的官方文档。 ### 回答2: Spring Security OAuth2.0是一个基于Spring框架的安全认证和访问控制框架,它实现了OAuth2.0协议并提供了OAuth2.0客户端和服务器的实现,可以帮助Spring应用程序保护和管理访问资源。 Spring Security OAuth2.0的实现主要包括客户端和服务器的认证和授权过程。在客户端认证过程中,首先会发送请求获取访问令牌,然后将访问令牌发送给资源服务器以访问所需的资源。在服务器认证过程中,首先要检验客户端是否有访问资源的权限,如果有则颁发授权码或访问令牌,否则返回错误信息。 在实现中,Spring Security OAuth2.0主要涉及到四个角色:资源拥有者、客户端、授权服务器和资源服务器。资源拥有者可以是用户,识别资源拥有者是通过认证授权服务器来完成的。客户端是向授权服务器申请OAuth2.0访问令牌的应用程序。授权服务器是用来对客户端进行身份验证和授权的服务器,它可以使用多种身份验证方式和批准策略来验证客户端的请求,然后授权它访问所需的资源。资源服务器是维护、提供API的服务器,它可以验证OAuth2.0访问令牌,然后允许或拒绝客户端的请求。 Spring Security OAuth2.0框架中提供了一些接口和类来实现OAuth2.0的认证和授权过程。例如,OAuth2AuthenticationProcessingFilter是用于授权客户端访问资源的过滤器,它首先对客户端的访问请求进行身份验证,然后检查是否有访问资源的权限。如果客户端有访问权限,则颁发访问令牌。 在实际使用中,Spring Security OAuth2.0可以与其他技术栈集成,例如Spring BootSpring Cloud、JavaEE等,可以实现用户级别、角色级别、API级别、组织级别等多种细粒度的访问控制方式,从而帮助企业实现灵活的访问控制。同时,Spring Security OAuth2.0框架也提供了一些扩展配置和插件,可以根据企业自身需求进行二次开发和定制,实现更加高效和安全的应用程序。 ### 回答3: Spring Security是一个功能强大的安全框架,提供了基于应用程序的安全性控制和身份验证机制。而OAuth2.0则是一种允许用户使用第三方应用程序访问资源的框架,并且该框架将安全性设计为一个核心功能。 Spring SecurityOAuth2.0可以结合使用来提高应用程序的安全性。Spring Security OAuth2.0是一个非常特殊的模块,它为OAuth2.0提供了完整的实现。 使用Spring Security OAuth2.0,我们可以实现以下功能: 1. 身份验证和授权管理:提供授权服务器和资源服务器来进行身份验证和授权的管理。 2. Token管理:生成和管理OAuth2.0令牌以确保安全性。 3. 支持多种授权类型:支持授权码模式、客户端模式密码模式、隐式模式等多种授权类型,实现不同场景下的资源访问控制。 4. 集成Spring BootSpring Security OAuth2.0被设计成与Spring Boot高度集成,方便易用。 5. 提供公开API:提供了一组公开API,方便第三方应用程序的接入。 Spring SecurityOAuth2.0的集成需要我们做以下几个步骤: 1. 在Spring Security配置文件中添加OAuth2.0配置。 2. 定义安全领域对象,包括用户、角色和授权管理等。 3. 实现OAuth2.0的授权服务器和资源服务器。 4. 配置OAuth2.0客户端,使其可以访问受保护的资源。 总之,Spring Security OAuth2.0能够帮助开发者集成身份验证和授权管理功能,并为第三方应用程序提供安全的访问资源方式。它为应用程序提供了更高级别的安全性和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值