OAuth 2 有四种授权模式,分别是授权码模式(authorization code)、简化模式(implicit)、密码模式(resource owner password credentials)、客户端模式(client credentials),具体 OAuth2 是什么,可以参考这篇文章(http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)
————————————————
上篇讲解的是授权码模式,本篇主要讲解密码模式。平常主要使用的就是这两种模式。(注:本篇基于上一篇的代码基础之上)
1.授权流程
1.客户端带着clientid,screteid,用户名,密码。到授权服务器获取token。
2.客户端获取到token之后,带着token访问服务。
3.服务获取客户端带过来的token,到授权服务器进行验证token的合法性。有效允许访问服务,无效反之。就是如此简单。
到这。我们开发人员需要实现的就第一,第二步。第三步由我们配置验证url,Spring Cloud OAuth2框架会自动帮我们完成验证。
项目组成authe-server 权限验证服务在上一篇博客已经实现,本篇只需要事项client-user用户需要访问的服务。
DemoApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
ResourceServerConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
/**
* Created by Administrator on 2020-06-12.
*/
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled =