filter java oauth_Spring Cloud入门-Oauth2授权的使用(Hoxton版本)

文章目录摘要OAuth2简介OAuth2相关名词解释四种授权模式两种常用的授权模式授权码模式密码Java

项目使用的Spring Cloud为Hoxton版本,Spring Boot为2.2.2.RELEASE版本

Spring Cloud入门系列汇总

摘要

Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2可以实现单点登录、令牌中继、令牌交换等功能,本文将对其结合Oauth2入门使用进行详细介绍。

OAuth2 简介

OAuth 2.0是用于授权的行业标准协议。OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等。

OAuth2 相关名词解释

Resource owner(资源拥有者):拥有该资源的最终用户,他有访问资源的账号密码;

Resource server(资源服务器):拥有受保护资源的服务器,如果请求包含正确的访问令牌,可以访问资源;

Client(客户端):访问资源的客户端,会使用访问令牌去获取资源服务器的资源,可以是浏览器、移动设备或者服务器;

Authorization server(授权服务器):用于授权用户的服务器,如果客户端授权通过,发放访问资源服务器的令牌。

四种授权模式

Authorization Code(授权码模式):正宗的OAuth2的授权模式,客户端先将用户导向授权服务器,登录后获取授权码,然后进行授权,最后根据授权码获取访问令牌;

Implicit(简化模式):和授权码模式相比,取消了获取授权码的过程,直接获取访问令牌;

Resource Owner Password Credentials(密码模式):客户端直接向用户获取用户名和密码,之后向授权服务器获取访问令牌;

Client Credentials(客户端模式):客户端直接通过客户端授权(比如client_id和client_secret)从授权服务器获取访问令牌。

两种常用的授权模式

授权码模式

(A)客户端将用户导向授权服务器;

(B)用户在授权服务器进行登录并授权;

©授权服务器返回授权码给客户端;

(D)客户端通过授权码和跳转地址向授权服务器获取访问令牌;

(E)授权服务器发放访问令牌(有需要带上刷新令牌)。

密码模式

(A)客户端从用户获取用户名和密码;

(B)客户端通过用户的用户名和密码访问授权服务器;

©授权服务器返回访问令牌(有需要带上刷新令牌)。

Oauth2的使用

创建oauth2-server模块

这里我们创建一个oauth2-server模块作为授权服务器来使用。

在pom.xml中添加相关依赖:

org.springframework.boot

spring-boot-starter-web

org.springframework.cloud

spring-cloud-starter-oauth2

org.springframework.cloud

spring-cloud-starter-security

在application.yml中进行配置:

server:

port: 9401

spring:

application:

name: oauth2-server

添加UserService实现UserDetailsService接口,用于加载用户信息:

@Service

public class UserService implements UserDetailsService {

private List userList;

@Autowired

private PasswordEncoder passwordEncoder;

@PostConstruct

public void initData() {

String password = passwordEncoder.encode("123456");

userList = new ArrayList<>();

userList.add(new User("jourwon",password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));

userList.add(new User("andy",password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));

userList.add(new User("mark",password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));

}

@Override

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

List findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());

if (!CollectionUtils.isEmpty(findUserList)) {

return findUserList.get(0);

} else {

throw new UsernameNotFoundException("用户名或密码错误");

}

}

}

添加授权服务器配置,使用@EnableAuthorizationServer注解开启:

@Configuration

@EnableAuthorizationServer

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired

private PasswordEncoder passwordEncoder;

@Autowired

private AuthenticationManager authenticationManager;

@Autowired

private UserService userService;

/** * 使用密码模式需要配置 * * @param endpoints * @throws Exception */

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

endpoints.authenticationManager(authenticationManager)

.userDetailsService(userService);

}

@Override

public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

clients.inMemory()

// 配置client_id

.withClient("admin")

// 配置client_secret

.secret(passwordEncoder.encode("admin123456"))

// 配置访问token的有效期

.accessTokenValiditySeconds(3600)

// 配置刷新token的有效期

.refreshTokenValiditySeconds(864000)

// 配置redirect_uri,用于授权成功后的跳转

.redirectUris("http://www.baidu.com")

// 配置申请的权限范围

.scopes("all")

// 配置grant_type,表示授权类型

.authorizedGrantTypes("authorization_code", "password");

}

}

添加资源服务器配置,使用@EnableResourceServer注解开启:

@Configuration

@EnableResourceServer

public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Override

public void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()

.anyRequest()

.authenticated()

.and()

.requestMatchers()

// 配置需要保护的资源路径

.antMatchers("/user/**");

}

}

添加SpringSecurity配置,允许授权相关路径的访问及表单登录:

@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

protected void configure(HttpSecurity http) throws Exception {

http.csrf()

.disable()

.authorizeRequests()

.antMatchers("/oauth/**", "/login/**", "logout/**")

.permitAll()

.anyRequest()

.authenticated()

.and()

.formLogin()

.permitAll();

}

}

添加需要登录的接口用于测试:

@RestController

@RequestMapping("/user")

public class UserController {

@GetMapping("/getCurrentUser")

public Object getCurrentUser(Authentication authentication) {

return authentication.getPrincipal();

}

}

授权码模式使用

启动oauth2-server服务;

输入账号密码进行登录操作:

登录后进行授权操作:

之后会浏览器会带着授权码跳转到我们指定的路径:

https://www.baidu.com/?code=cbM53v&state=normal

使用Basic授权通过client_id和client_secret构造一个Authorization头信息;

在body中添加以下参数信息,通过POST请求获取访问令牌;

密码模式使用

使用Basic授权通过client_id和client_secret构造一个Authorization头信息;

在body中添加以下参数信息,通过POST请求获取访问令牌;

使用到的模块

springcloud-learning

└── oauth2-server -- oauth2授权测试服务

项目源码地址

本文由来源 ThinkWon的博客,由 system_mush 整理编辑,其版权均为 ThinkWon的博客 所有,文章内容系作者个人观点,不代表 Java架构师必看 对观点赞同或支持。如需转载,请注明文章来源。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值