Springcloud Oauth2 进阶篇

本文深入探讨了在微服务架构中使用OAuth2进行鉴权,并结合Redis实现Token的分布式存储。详细介绍了Spring Cloud OAuth2的配置过程,包括依赖、属性配置及自定义认证处理。

上一篇写到Springcloud Oauth2 基础篇,其token存储依靠JWT。本篇讲解基于redis存储token,进行分布式微服务架构设计。

环境

       

    ubuntu16.04

    docker18.04

    k8s1.13.x +

    maven3.5.3

    java1.8 +

    springboot 2.1.8

代码结构:

— cas-server #鉴权中心

— admin-web #后台管理服务

— order-service #订单服务

鉴权中心 cas-server:

配入依赖:

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


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <swagger.version>2.6.1</swagger.version>
    <xstream.version>1.4.7</xstream.version>
    <pageHelper.version>4.1.6</pageHelper.version>
    <fastjson.version>1.2.51</fastjson.version>
    <springcloud.version>Greenwich.SR4</springcloud.version>
    <springcloud.kubernetes.version>1.1.1.RELEASE</springcloud.kubernetes.version>
    <mysql.version>5.1.46</mysql.version>
  </properties>


  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${springcloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  
  <dependencies>
      <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
  
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <!-- spring-cloud-starter-oauth2包含了 spring-cloud-starter-security -->
        <!-- <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency> -->
        
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.6.3</version>
        </dependency>
        
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        
        <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        </dependency>
    
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.2</version>
    </dependency>
    
    <!-- swagger -->
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>${swagger.version}</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>${swagger.version}</version>
    </dependency>
    
    <!--分页插件-->  
      <dependency>
        <groupId>com.github.pagehelper</groupId>  
        <artifactId>pagehelper</artifactId>  
        <version>${pageHelper.version}</version>
      </dependency>
    
    <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
        
        <!-- datasource pool-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>
        
        <!-- 对redis支持,引入的话项目缓存就支持redis了,所以必须加上redis的相关配置,否则操作相关缓存会报异常 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>${fastjson.version}</version>
    </dependency>
    
    <dependency>
      <groupId>org.jsoup</groupId>
      <artifactId>jsoup</artifactId>
      <version>1.11.3</version>
    </dependency>


    </dependencies>

配置文件:bootstrap.yaml

management:
  endpoint:
    restart:
      enabled: true
    health:
      enabled: true
    info:
      enabled: true


spring:
  application:
    name: cas-server
  redis: #redis相关配置
    database: 8
    host: localhost
    port: 6379
    password: sofawang #有密码时设置
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
    timeout: 10000ms
    
    
  http:
    encoding:
      charset: UTF-8
      enabled: true
      force: true
  mvc:
    throw-exception-if-no-handler-found: true
  main:
    allow-bean-definition-overriding: true # 当遇到同样名称时,是否允许覆盖注册

application.yaml:

server:
  port: 2000
  undertow:
    accesslog:
      enabled: false
      pattern: combined
  servlet:
    session:
      timeout: PT120M
  
logging:
  path: /data/${spring.application.name}/logs




#sso_redirect_urls: http://localhost:2001/login,http://localhost:2003/login


client:
  http:
    request:
      connectTimeout: 8000
      readTimeout: 30000
      
mybatis:
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: com.damon.*.model


新建启动类:

package com.damon;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


/**
 * 
 * 配置最多的就是认证服务端,验证账号、密码,存储 token,检查 token ,刷新 token 等都是认证服务端的工作
 * @author Damon 
 * @date 2020年1月13日 下午2:29:42
 *
 */
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.damon"})
//@SpringBootApplication(scanBasePackages = { "com.damon" })
public class CasApp {
  public static void main(String[] args) {
    SpringApplication.run(CasApp.class, args);
  }
}


认证服务器配置:

package com.damon.config;


import java.util.ArrayList;
import java.util.List;


import javax.sql.DataSource;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
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.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;


import com.damon.component.JwtTokenEnhancer;
import com.damon.login.service.LoginService;


/**
 * 
 * 认证服务器配置
 * @author Damon 
 * @date 2020年1月13日 下午3:03:30
 *
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private PasswordEncoder passwordEncoder;


    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired
    private LoginService loginService;


    @Autowired
    @Qualifier("redisTokenStore")
    private TokenStore tokenStore;
    
    @Autowired
    private Environment env;
    
    
    @Autowired
    private DataSource dataSource;
    
    /**
     * redis token 方式
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager) //支持 password 模式
                .userDetailsService(loginService)
                .tokenStore(tokenStore);


    }


    /**
     * 客户端配置(给谁发令牌)
     * 不同客户端配置不同
     * 
     * authorizedGrantTypes 可以包括如下几种设置中的一种或多种:
      authorization_code:授权码类型。需要redirect_uri
      implicit:隐式授权类型。需要redirect_uri
      password:资源所有者(即用户)密码类型。
      client_credentials:客户端凭据(客户端ID以及Key)类型。
      refresh_token:通过以上授权获得的刷新令牌来获取新的令牌。
     
     accessTokenValiditySeconds:token 的有效期
     scopes:用来限制客户端访问的权限,在换取的 token 的时候会带上 scope 参数,只有在 scopes 定义内的,才可以正常换取 token。
     * @param clients
     * @throws Exception
     * @author Damon 
     * @date 2020年1月13日
     *
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("admin-web")
                .secret(passwordEncoder.encode("admin-web-123"))
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(864000)//配置刷新token的有效期
                .autoApprove(true) //自动授权配置
                .scopes("all")//配置申请的权限范围
                .authorizedGrantTypes("password", "authorization_code", "client_credentials", "refresh_token")//配置授权模式
                .redirectUris("http://localhost:2001/login")//授权码模式开启后必须指定
                .and()
                .withClient("order-service")
                .secret(passwordEncoder.encode("order-service-123"))
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(864000)//配置刷新token的有效期
                .autoApprove(true) //自动授权配置
                .scopes("all")
                .authorizedGrantTypes("password", "authorization_code", "client_credentials", "refresh_token")//配置授权模式
                .redirectUris("http://localhost:2003/login")//授权码模式开启后必须指定
                //.authorizedGrantTypes("authorization_code", "password", "refresh_token")//配置授权模式:authorization_code授权码模式、密码模式
                ;
    }
    
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
      security.allowFormAuthenticationForClients();//是允许客户端访问 OAuth2 授权接口,否则请求 token 会返回 401
      security.checkTokenAccess("isAuthenticated()");//是允许已授权用户访问 checkToken 接口
        security.tokenKeyAccess("isAuthenticated()"); // security.tokenKeyAccess("permitAll()");获取密钥需要身份认证,使用单点登录时必须配置,是允许已授权用户获取 token 接口
    }
}


Spring WEBSecurity配置:

package com.damon.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


/**
 * 
 * SpringSecurity配置
 * @author Damon 
 * @date 2020年1月13日 下午3:03:55
 *
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


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


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


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/oauth/**", "/login/**")//"/logout/**"
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**", "/js/**", "/plugins/**", "/favicon.ico");
    }
}


资源服务器配置:

package com.damon.config;


import org.springframework.beans.factory.annotation.Autowired;
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;


/**
 * 
 * 资源服务器配置
 * @author Damon 
 * @date 2020年1月13日 下午3:03:48
 *
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  
  
  @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        
                .exceptionHandling()
            .authenticationEntryPoint(new JWTAuthenticationEntryPoint())
            //.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
            .and()
        
                .requestMatchers().antMatchers("/api/**")
                .and()
                .authorizeRequests()
                .antMatchers("/api/**").authenticated()
                .and()
                .httpBasic();
    }
}


自定义认证失败结果处理:

package com.damon.config;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;


import com.alibaba.fastjson.JSON;
import com.damon.commons.Response;


/**
 * 
 * 统一结果处理
 * 
 * @author Damon 
 * @date 2020年1月16日 上午8:11:44
 *
 */


public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
  /**
   *
   * @author Damon
   * @date 2020年1月16日
   *
   */
  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException authException) throws IOException, ServletException {


    //response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    //response.setStatus(HttpStatus.OK.value());
    
        //response.setHeader("Access-Control-Allow-Origin", "*");  //gateway已加,无需再加
        //response.setHeader("Access-Control-Allow-Headers", "token");
        //解决低危漏洞点击劫持 X-Frame-Options Header未配置
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
    
    response.getWriter()
    .write(JSON.toJSONString(Response.ok(response.getStatus(), -2, authException.getMessage(), authException.getMessage())));
    /*response.getWriter()
        .write(JSON.toJSONString(Response.ok(200, -2, "Internal Server Error", authException.getMessage())));*/
  }
}


Redis Store:

package com.damon.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;


/**
 * 使用redis存储token的配置
 * @author Damon 
 * @date 2020年1月13日 下午3:03:19
 *
 */
@Configuration
public class RedisTokenStoreConfig {


    @Autowired
    private RedisConnectionFactory redisConnectionFactory;


    @Bean
    public TokenStore redisTokenStore (){
        return new RedisTokenStore(redisConnectionFactory);
    }
}


到目前为止,鉴权中心主要代码已经贴出来了,如果需要加数据库等,自己可根据需要添加,此处代码不贴了。

资源服务 admin-web:

maven 依赖配置差不多,这里就不再赘述了。

配置文件:bootstrap.yaml

spring:
  application:
    name: admin-web
  #redis: #redis相关配置
    #password: 123456 #有密码时设置
  http:
    encoding:
      charset: UTF-8
      enabled: true
      force: true
  mvc:
    throw-exception-if-no-handler-found: true
  main:
    allow-bean-definition-overriding: true # 当遇到同样名称时,是否允许覆盖注册
    
    
cas-server-url: http://localhost:2000


security:
  oauth2: #与cas-server对应的配置
    client:
      client-id: admin-web
      client-secret: admin-web-123
      user-authorization-uri: ${cas-server-url}/oauth/authorize #是授权码认证方式需要的
      access-token-uri: ${cas-server-url}/oauth/token #是密码模式需要用到的获取 token 的接口
    resource:
      #jwt: #jwt存储token时开启
        #key-uri: ${cas-server-url}/oauth/token_key
        #key-value: test_jwt_sign_key
      id: admin-web
      user-info-uri: ${cas-server-url}/api/user
      prefer-token-info: false
      #token-info-uri: 
    authorization:
      check-token-access: ${cas-server-url}/oauth/check_token #当此web服务端接收到来自UI客户端的请求后,需要拿着请求中的 token 到认证服务端做 token 验证,就是请求的这个接口

配置文件:application.yaml

server:
  port: 2001
  undertow:
    accesslog:
      enabled: false
      pattern: combined
  servlet:
    session:
      timeout: PT120M
      cookie:
        name: ADMIN-WEB-SESSIONID #防止Cookie冲突,冲突会导致登录验证不通过
        
logging:
  path: /data/${spring.application.name}/logs


client:
  http:
    request:
      connectTimeout: 8000
      readTimeout: 30000
      
mybatis:
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: com.damon.*.model


客户端启动类:

package com.damon;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


/**
 * @author Damon 
 * @date 2020年1月13日 下午3:23:06
 *
 */


@EnableOAuth2Sso
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.damon"})
public class AdminApp {


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


}

Spring WEBSecurity配置:

package com.damon.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


/**
 * 
 * 在接口上配置权限时使用
 * @author Damon 
 * @date 2020年1月13日 下午3:29:49
 *
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(101)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}


资源服务器配置:

package com.damon.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;


import javax.servlet.http.HttpServletResponse;


/**
 * 
 * 
 * @author Damon 
 * @date 2020年1月16日 下午6:28:35
 *
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        
                .exceptionHandling()
            .authenticationEntryPoint(new JWTAuthenticationEntryPoint())
            //.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
            .and()
        
                .requestMatchers().antMatchers("/api/**")
                .and()
                .authorizeRequests()
                .antMatchers("/api/**").authenticated()
                .and()
                .httpBasic();
    }
}

自定义结果处理:

package com.damon.config;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;


import com.alibaba.fastjson.JSON;
import com.damon.commons.Response;


/**
 * 
 * 统一结果处理
 * 
 * @author Damon 
 * @date 2020年1月16日 上午11:11:44
 *
 */


public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
  /**
   *
   * @author Damon
   * @date 2020年1月16日
   *
   */
  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException authException) throws IOException, ServletException {


    //response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    //response.setStatus(HttpStatus.OK.value());
    
        //response.setHeader("Access-Control-Allow-Origin", "*");  //gateway已加,无需再加
        //response.setHeader("Access-Control-Allow-Headers", "token");
        //解决低危漏洞点击劫持 X-Frame-Options Header未配置
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
    
    response.getWriter()
    .write(JSON.toJSONString(Response.ok(response.getStatus(), -2, authException.getMessage(), authException.getMessage())));
    /*response.getWriter()
        .write(JSON.toJSONString(Response.ok(200, -2, "Internal Server Error", authException.getMessage())));*/
  }
  
}

到目前为止,鉴权中心、资源服务代码已经贴出。

我们可以利用上一篇提供的各种方式进行测试。

接下来看看资源权限问题:

package com.damon.user.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import com.damon.commons.Response;
import com.damon.user.service.UserService;


/**
 * 
 * 
 * @author Damon 
 * @date 2020年1月13日 下午3:31:07
 *
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
  
  private static final Logger logger = LoggerFactory.getLogger(UserController.class);
  
  @Autowired
  private UserService userService;
  
    @GetMapping("/getCurrentUser")
    @PreAuthorize("hasAuthority('admin')")
    public Object getCurrentUser(Authentication authentication) {
      logger.info("test password mode");
        return authentication;
    }


    @PreAuthorize("hasAuthority('admin')")
    @GetMapping("/auth/admin")
    public Object adminAuth() {
      logger.info("test password mode");
        return "Has admin auth!";
    }
    
    @GetMapping(value = "/get")
    //@PreAuthorize("hasAuthority('admin')")
    @PreAuthorize("hasRole('admin')")//无效
    public Object get(Authentication authentication){
        //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        authentication.getCredentials();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
        String token = details.getTokenValue();
        return token;
    }
    
    @GetMapping("/getUserInfo")
    @PreAuthorize("hasAuthority('admin')")
    public Response<Object> getUserInfo(Authentication authentication) {
      logger.info("test password mode");
      Object principal = authentication.getPrincipal();
      if(principal instanceof String) {
        String username = (String) principal;
        return userService.getUserByUsername(username);
      }
    return null;
    }


}


在这个接口类中,其中用到的权限控制注解:hasAuthority,但也存在hasRole注解,但这个似乎与hasAuthority不等效,大家如想了解,可百度下区别。

以上就是今天的分享,欢迎大家围观,也可关注、加入星球。

<think>好的,我需要帮用户规划学习Spring Cloud Alibaba微服务的路径,从入门到进阶。首先,我得回想一下用户提到的引用内容,尤其是引用[1]关于版本兼容性的问题,还有引用[3]提到的消息队列解耦应用的部分。这些引用可能需要整合到教程中,确保用户了解版本选择和核心组件如消息队列的应用。 接下来,我应该分阶段来构建教程。入门阶段需要涵盖基础概念和环境搭建,这里需要强调Spring Boot,因为它是Spring Cloud的基础。引用[2]提到Spring Boot的Profile功能,可以用来管理不同环境的配置,这点很重要,应该在配置管理部分详细说明。 然后,核心组件部分要包括Nacos作为注册和配置中心,Sentinel负责流量控制,Seata处理分布式事务,以及RocketMQ用于消息队列。这些组件都是Spring Cloud Alibaba的关键,需要逐一解释它们的作用和使用方法。特别是引用[3]中提到的消息队列解耦系统,可以结合RocketMQ的实战案例来说明。 进阶阶段需要深入微服务的高级特性,比如分布式事务和链路追踪。这里可以引用Seata来处理事务问题,同时结合Sleuth和Zipkin进行监控。安全方面,Spring Security和OAuth2也是必须涵盖的内容,确保微服务的安全性。 项目实战部分,通过电商案例将各个组件串联起来,让用户有实际的操作经验。运维部署阶段,Docker和Kubernetes的整合是当前的主流,需要指导用户如何进行容器化部署和监控。 最后,持续学习部分推荐官方文档和社区资源,帮助用户保持知识的更新。同时,要生成相关问题,引导用户深入思考各个组件的应用和优化,例如版本兼容性问题、配置管理的最佳实践,以及消息队列在系统解耦中的具体作用。 需要注意的是,所有引用的内容要自然地融入教程中,比如在讲配置管理时提到引用[2],在消息队列部分引用[3]。版本选择部分则引用[1]的内容,确保用户理解版本匹配的重要性。整个回答结构要清晰,步骤明确,帮助用户逐步掌握Spring Cloud Alibaba的各个方面。</think>### Spring Cloud Alibaba 微服务学习路径规划 以下是从入门到进阶的系统化学习框架,整合Spring Cloud Alibaba核心组件与微服务设计思想,结合引用内容的关键知识点: --- #### **第一阶段:基础入门** 1. **环境搭建与版本选择** - 安装JDK 8+、Maven 3.6+、IDEA开发工具 - 根据**Spring Boot与Spring Cloud Alibaba版本兼容性**选择稳定组合[^1],例如: $$ \text{Spring Boot 2.6.x} + \text{Spring Cloud 2021.0.x} + \text{Spring Cloud Alibaba 2021.0.5.0} $$ - 通过Spring Initializr快速生成项目模板:https://start.spring.io 2. **Spring Boot核心知识** - 配置文件格式(YAML/Properties)与多环境配置(`spring.profiles.active`)[^2] - 自动装配原理与`@SpringBootApplication`注解 - RESTful API开发与`@RestController` 3. **微服务基础概念** - 服务注册与发现(Service Registry) - 配置中心(Configuration Management) - 服务调用(RPC/HTTP)与负载均衡 --- #### **第二阶段:核心组件实战** 1. **Nacos:注册中心与配置中心** - 部署Nacos Server(单机模式/Docker) - 服务注册与发现:`spring-cloud-starter-alibaba-nacos-discovery` - 动态配置管理:`spring-cloud-starter-alibaba-nacos-config` ```yaml # 示例:Nacos配置中心连接 spring: cloud: nacos: config: server-addr: localhost:8848 file-extension: yaml ``` 2. **Sentinel:流量控制与熔断降级** - 定义资源与规则(QPS、线程数、熔断策略) - 集成Feign实现服务熔断 - 实时监控与仪表盘 3. **Seata:分布式事务** - AT模式原理与全局事务注解`@GlobalTransactional` - 事务协调器(TC)与资源管理器(RM)部署 4. **RocketMQ:消息队列** - 消息生产与消费模型(Producer/Consumer) - 消息可靠性投递(事务消息) - **应用解耦实战**:订单系统与库存系统通过消息队列异步通信[^3] --- #### **第三阶段:进阶架构设计** 1. **微服务高级特性** - 网关层:Spring Cloud Gateway实现路由与鉴权 - 链路追踪:Sleuth + Zipkin - 服务网格:Istio与Spring Cloud整合 2. **安全与权限控制** - OAuth2协议与Spring Security整合 - JWT令牌在微服务间的传递 3. **性能优化** - 缓存策略:Redis分布式缓存 - 数据库分库分表:ShardingSphere --- #### **第四阶段:项目实战与运维** 1. **电商系统实战案例** - 模块划分:订单服务、库存服务、支付服务、用户服务 - 技术整合:Nacos + Sentinel + Seata + RocketMQ 2. **容器化部署** - Docker镜像构建与Docker Compose编排 - Kubernetes集群部署(Deployment/Service/Ingress) 3. **监控与日志** - Prometheus + Grafana监控微服务指标 - ELK(Elasticsearch, Logstash, Kibana)日志分析 --- #### **持续学习资源** - 官方文档:[Spring Cloud Alibaba GitHub](https://github.com/alibaba/spring-cloud-alibaba) - 社区实践:Alibaba Cloud Native Community - 书籍推荐:《Spring Cloud Alibaba微服务原理与实战》 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值