Spring cloud入门-OAuth 2.0(二)

创建oauth2-server

依赖

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

配置

server:
  port: 9401

spring:
  application:
    name: oauth2-server

UserService

UserService 的作用就是加载用户信息

package com.zglx.oauth.service;

import com.example.common.model.User;
import com.zglx.oauth.model.OauthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 模拟用户存储
 * @Author: Zlx
 * @Date: 2021/10/17 4:57 下午
 */
@Service
public class UserService implements UserDetailsService {
	private static List<OauthUser> userList;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@PostConstruct
	public void init() {
		String password = passwordEncoder.encode("123");
		userList = new ArrayList<>(3);
		userList.add(new OauthUser("zglx", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
		userList.add(new OauthUser("andy", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
		userList.add(new OauthUser("mark", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
	}

	/**
	 * 用户登录的
	 *  
	 * @param  username 账号
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 暂时不校验密码
		List<OauthUser> collect = userList.stream().filter(item ->
				item.getUsername().equals(username))
				.collect(Collectors.toList());
		return collect.get(0);
	}
}

AuthorizationServerConfig

授权服务器,作用是发送令牌给客户端,需要使用@EnableAuthorizationServer开启

package com.zglx.oauth.config;

import com.zglx.oauth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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;

/**
 * @Description: 授权服务器
 * @Author: Zlx
 * @Date: 2021/10/17 5:09 下午
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private UserService userService;

	/**
	 * 使用密码模式需要配置
	 *
	 * @param endpoints endpoints
	 * @throws Exception
	 */
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.authenticationManager(authenticationManager)
				// 配置用户数据源,登录的时候会执行userService的loadUserByUsername方法
				// 登录地址
				// http://localhost:9401/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all&state=normal
				.userDetailsService(userService);
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory()
				// 配置client_id
				.withClient("admin")
				// 配置client_secret
				.secret(passwordEncoder.encode("admin"))
				// 配置访问token的有效期
				.accessTokenValiditySeconds(3600)
				// 配置刷新token的有效期
				.refreshTokenValiditySeconds(864000)
				// 配置redirect_uri,用于授权成功后的跳转
				.redirectUris("http://www.baidu.com")
				// 配置申请的权限范围
				.scopes("all")
				// 配置grant_type,表示授权类型
				.authorizedGrantTypes("authorization_code", "password");
	}
}

ResourceServerConfig

资源服务器,需要使用@EnableResourceServer开启

package com.zglx.oauth.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: Zlx
 * @Date: 2021/10/17 5:19 下午
 */

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				.anyRequest()
				.authenticated()
				.and()
				.requestMatchers()
				// 配置需要保护的资源路径
				.antMatchers("/user/**");
	}
}

SpringSecurity

允许授权相关路径的访问,客户端需要访问的路径都需要在这里配置

package com.zglx.oauth.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.web.builders.HttpSecurity;
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;

/**
 * @Description:Security相关配置
 * @Author: Zlx
 * @Date: 2021/10/17 5:21 下午
 */
@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();
	}
}

UserController

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication.getPrincipal();
    }

}

授权模式的使用

获取code

启动oauth-server服务,然后访问
http://localhost:9401/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all&state=normal
在这里插入图片描述
在这里插入图片描述

之后浏览器会跳转,并且带上授权码
http://www.baidu.com
在这里插入图片描述

获取assce_token

使用授权码请求该地址获取访问令牌:http://localhost:9100/oauth/token
第一步,先设置Headers
在这里插入图片描述
第二步,发布表单请求获取assce_token
在这里插入图片描述
在这里插入图片描述
第三步,调用测试接口,
http://localhost:9100/user/getCurrentUser

在这里插入图片描述

密码模式的使用

在这里插入图片描述

在这里插入图片描述

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值