2019独角兽企业重金招聘Python工程师标准>>>
package com.icecloud.cloud.test.oauthTest_1;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.ManagementServerProperties;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
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.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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@EnableAuthorizationServer
@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
public class App extends WebSecurityConfigurerAdapter {
/**
* 需要权限的action
*/
@RequestMapping({ "/test" })
public Map<String, String> test() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("nametest", "12222");
return map;
}
/**
* 需要权限并且提供token才能访问的action
*/
@RequestMapping({ "/se" })
public Map<String, String> se() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("se", "3333");
return map;
}
/**
* 不需要权限的action
*/
@RequestMapping({ "/","" })
public String index() {
return "index";
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
}
/**
* 资源服务器
* @author penghaozhong
*
*/
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId("app").stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/se")
.and()
.authorizeRequests()
.antMatchers("/se").access("#oauth2.hasScope('read')");
}
}
/**
* oauth2 服务端
* @author penghaozhong
*
*/
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("tonr").secret("secret").authorizedGrantTypes("authorization_code")
.scopes("read");
}
}
}
一个完成的oauth2 例子 。服务端和资源服务器同为一个。下面进行代码拆分理解。
本例子中有三个重要的组件:security ResourceServer AuthorizationServer
一. 继承 WebSecurityConfigurerAdapter 就完成了security的组装工作。
public class App extends WebSecurityConfigurerAdapter
WebSecurityConfigurerAdapter 默认是要求进行账号密码登录操作的,即使你没有编写.formLogin(),因为系统用上了默认配置。
WebSecurityConfigurerAdapter 类中:有这段代码
protected void configure(HttpSecurity http) throws Exception {
logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
}
security账号密码配置方式,记住这里的账号密码是用户登录时用的。配置有2种形式:
1. 编写代码
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
}
2:编写配置文件
二. 配置oauth2 AuthorizationServer 继承AuthorizationServerConfigurerAdapter。填入客户端id和密码,授权模式,权限范围。这里简单实现保存到缓存中。
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("tonr").secret("secret").authorizedGrantTypes("authorization_code")
.scopes("read");
}
三. 配置资源服务器 ResourceServer 哪些资源需要通过oauth2提供的服务的,需要编写代码限制。比如/se 这个请求地址就是需要进行oauth2 授权后才能访问的信息。
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/se")
.and()
.authorizeRequests()
.antMatchers("/se").access("#oauth2.hasScope('read')");
}
代码编写已经理解完成。下面进行实际测试工作吧。
四. 请求授权
这里我用的postman进行调试的。用到authorization的oauth2.0功能 ,很方便进行调试工作。各个参数按照要求填入即可。点击请求后在后台日志中会得到code。
四. 获取token
这里需要用上一把的code值去换取token,获取token时就用post方式获取。填入需要参数后,你会发现这里有个坑。这里卖个关子,如果你没有遇到没有解决又没太多时间去解决的话,留言即可。
五. 获取资源数据
大工搞成,希望这篇文章能帮到需要的朋友们。半夜睡不着可以起来调程序,很有乐趣!