基于spring-security-oauth2认证授权服务介绍与使用(一)

1、springCloud Oauth2 基本介绍

OAuth:OAuth(开放授权)是一个开放标准,允许用户授权第三方网站访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方网站或分享他们数据的所有内容。
在Spring Cloud需要使用oauth2来实现多个微服务的统一认证授权,通过向OAUTH服务发送某个类型的grant type进行集中认证和授权,从而获得access_token,而这个token是受其他微服务信任的,我们在后续的访问可以通过access_token来进行,从而实现了微服务的统一认证授权。
客户端根据约定的ClientID、ClientSecret、Scope来从Access Token URL地址获取AccessToken,并经过AuthURL认证,用得到的AccessToken来访问其他资源接口。
Spring Cloud oauth2 需要依赖Spring security

2、Oauth2 角色划分

  1. Resource Sever --> 被授权访问的资源
  2. Authorization Server --> Oauth2认证授权中心
  3. Resource Owner --> 用户
  4. Client --> 使用API 的客户端(比如:Android、IOS、web app…)

3、Oauth2的四种授权方式

  1. 授权码模式(authorization code)用在客户端与服务端应用之间授权
  2. 简化模式(implicit)用在移动ap或者web app(这些app是在用户设备上的,如在手机上调用微信来认证授权)
  3. 密码模式(resource owner password credentials)应用直接都是受信任的
  4. 客户端模式(client credentials)用在应用API访问

4、Oauth2环境搭建

目录结构及项目地址:spring-security-oauth2
在这里插入图片描述

4.1、搭建 spring-security-oauth2 项目[pom]

4.1.1、pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
 </parent>

4.2、搭建oauth2-server 认证授权中心服务

4.2.1、pom.xml

<dependencies>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- springboot整合freemarker -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-->spring-boot 整合security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- spring-cloud-starter-oauth2 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>

    </dependencies>

    <!-- 管理依赖 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.M7</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!-- 注意: 这里必须要添加, 否者各种依赖有问题 -->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

4.2.2、application.yml

server:
  port: 9090

4.2.3、配置信息

package com.redmaple.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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.provisioning.InMemoryUserDetailsManager;

/**
 * @Description 配置授权中心信息
 * @Author redMaple-gi
 * @Date 2020/6/19 13:39
 * @Version 1.0
 */
@Configuration
@EnableAuthorizationServer  //开启oauth2认证授权中心服务
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    // accessToken过期时间-1小时
    private static int accessTokenValiditySeconds = 3600;
    // accessToken的刷新时间
    private static int refreshTokenValiditySeconds = 3600;

    /**
     * 应该读取数据库,先固定写
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("client_1")
                .secret(passwordEncoder().encode("123456"))
//                .authorizedGrantTypes("authorization_code","refresh_token")     //授权码模式
//                .authorizedGrantTypes("password")   //密码模式
//                .authorizedGrantTypes("client_credentials")   //客户端模式
                //混合模式
                .authorizedGrantTypes("authorization_code","password","refresh_token")
                //回调地址
                .redirectUris("http://www.baidu.com")
                .accessTokenValiditySeconds(accessTokenValiditySeconds)
                .refreshTokenValiditySeconds(refreshTokenValiditySeconds)
                .scopes("all");

    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证
        security.allowFormAuthenticationForClients();
        // 允许check_token 访问
        security.checkTokenAccess("permitAll()");
    }

    /**
     * 设置token类型
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager())
            .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
    }

    @Bean
    public AuthenticationManager authenticationManager(){
        AuthenticationManager authenticationManager = new AuthenticationManager() {
            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                return daoAuthenticationProvider().authenticate(authentication);
            }
        };
        return authenticationManager;
    }


    @Bean
    public AuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService());
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }

    /**
     * 这里是用户名和密码,需要从数据库读取
     * 测试先固定
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();
        userDetailsService.createUser(User.withUsername("redmaple")
                .password(passwordEncoder().encode("123456"))
                .authorities("ROLE_USER").build()
        );
        userDetailsService.createUser(User.withUsername("admin")
                .password(passwordEncoder().encode("123456"))
                .authorities("ROLE_USER").build()
        );
        return userDetailsService;
    }

    /**
     * 加密方式
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

这里必须要加上SecurityConfig 配置文件,否则会报错 User must be authenticated with Spring Security before authorization can be completed 错误,因为访问请求没有放行。

package com.redmaple.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

/**
 * @Description 访问接口报错
 * User must be authenticated with Spring Security before authorization can be completed.
 * 需要开发权限,允许所有的接口访问进来
 * @Author redMaple-gi
 * @Date 2020/6/19 14:13
 * @Version 1.0
 */
@Component
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**")
                .fullyAuthenticated().and().formLogin();
    }
}

4.2.4、启动服务

@SpringBootApplication
public class AppOauth2Server {
    public static void main(String[] args) {
        SpringApplication.run(AppOauth2Server.class,args);
    }
}

4.3、搭建oauth2-resources-order 普通微服务,验证授权服务

4.3.1、pom.xml

<dependencies>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- springboot整合freemarker -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-->spring-boot 整合security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>

    </dependencies>

    <!-- 管理依赖 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.M7</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!-- 注意: 这里必须要添加, 否者各种依赖有问题 -->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

4.3.2、application.yml

server:
  port: 9091
logging:
  level:
    org.springframework.security: DEBUG

security:
  oauth2:
    resource:
      ## 从认证授权中心上验证token
      token-info-uri: http://localhost:9090/oauth/check_token
      prefer-token-info: true
    client:
      access-token-uri: http://localhost:9090/oauth/token
      user-authorization-uri: http://localhost:9090/oauth/authorize
      ## appid
      client-id: client_1
      ## appSecret
      client-secret: 123456

4.3.3、配置信息

package com.redmaple.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

/**
 * @Description 配置拦截设置
 * @Author redMaple-gi
 * @Date 2020/6/19 14:51
 * @Version 1.0
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 对接口/api/order/** 进行拦截
        http.authorizeRequests().antMatchers("/api/order/**").authenticated();
    }
}

4.3.4、认证授权接口

package com.redmaple.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author redMaple-gi
 * @Date 2020/6/19 14:54
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @GetMapping("/getOrder")
    public String getOrder(){
        System.out.println("This is my first time I've intercepted a request with OAuth2!");
        return "This is my first time I've intercepted a request with OAuth2!";
    }
}

4.3.5、启动服务

package com.redmaple;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;

/**
 * @Description
 * @Author redMaple-gi
 * @Date 2020/6/19 14:50
 * @Version 1.0
 */
@SpringBootApplication
@EnableOAuth2Sso
public class AppOauth2Order {
    public static void main(String[] args) {
        SpringApplication.run(AppOauth2Order.class, args);
    }
}

5、如何测试认证授权中心服务和访问资源服务器

接下来就是测试如何使用oauth2-server和oauth2-resources-order服务
下一篇:基于spring-security-oauth2认证授权服务介绍与使用(二)
项目地址:https://gitee.com/kuiwang2/spring-security-oauth2.git
参考地址:蚂蚁课堂

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章