spring oauth2 配置流程

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 例子 。服务端和资源服务器同为一个。下面进行代码拆分理解。java

本例子中有三个重要的组件:security  ResourceServer AuthorizationServerweb

一.  继承 WebSecurityConfigurerAdapter 就完成了security的组装工做。

public class App extends WebSecurityConfigurerAdapter

WebSecurityConfigurerAdapter 默认是要求进行帐号密码登陆操做的,即便你没有编写.formLogin(),由于系统用上了默认配置。spring

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')");
		}

代码编写已经理解完成。下面进行实际测试工做吧。session

四. 请求受权

这里我用的postman进行调试的。用到authorization的oauth2.0功能 ,很方便进行调试工做。各个参数按照要求填入便可。点击请求后在后台日志中会获得code。app

四. 获取token

这里须要用上一把的code值去换取token,获取token时就用post方式获取。填入须要参数后,你会发现这里有个坑。这里卖个关子,若是你没有遇到没有解决又没太多时间去解决的话,留言便可。less

五. 获取资源数据

大工搞成,但愿这篇文章能帮到须要的朋友们。半夜睡不着能够起来调程序,颇有乐趣!ide

相关文章
相关标签/搜索