栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring cloud入门-OAuth 2.0(二)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring cloud入门-OAuth 2.0(二)

OAuth 2.0的使用
  • 创建oauth2-server
  • UserService
  • AuthorizationServerConfig
  • ResourceServerConfig
  • SpringSecurity
  • UserController
  • 授权模式的使用
    • 获取code
    • 获取assce_token
  • 密码模式的使用

创建oauth2-server

依赖


	org.springframework.boot
	spring-boot-starter-web


	org.springframework.cloud
	spring-cloud-starter-oauth2


	org.springframework.cloud
	spring-cloud-starter-security


配置

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;


@Service
public class UserService implements UserDetailsService {
	private static List 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")));
	}

	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 暂时不校验密码
		List 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;


@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private UserService userService;

	
	@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;



@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				.anyRequest()
				.authenticated()
				.and()
				.requestMatchers()
				// 配置需要保护的资源路径
				.antMatchers("/user
@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

密码模式的使用

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/331640.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号