Springboot开发OAuth2认证授权与资源服务器操作

设计并开发一个开放平台。

一、设计:

网关可以 与认证授权服务合在一起,也可以分开。

二、开发与实现:

用Oauth2技术对访问受保护的资源的客户端进行认证与授权。

Oauth2技术应用的关键是:

1)服务器对OAuth2客户端进行认证与授权。

2)Token的发放。

3)通过access_token访问受OAuth2保护的资源。

选用的关键技术:Springboot, Spring-security, Spring-security-oauth2。

提供一个简化版,用户、token数据保存在内存中,用户与客户端的认证授权服务、资源服务,都是在同一个工程中。现实项目中,技术架构通常上将用户与客户端的认证授权服务设计在一个子系统(工程)中,而资源服务设计为另一个子系统(工程)。

1、Spring-security对用户身份进行认证授权:

主要作用是对用户身份通过用户名与密码的方式进行认证并且授权。

package com.banling.oauth2server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
    	//用户信息保存在内存中
		//在鉴定角色roler时,会默认加上ROLLER_前缀
        auth.inMemoryAuthentication().withUser("user").password("user").roles("USER").and()
        	.withUser("test").password("test").roles("TEST");
    }

	@Override
    protected void configure(HttpSecurity http) throws Exception {
		http.formLogin() //登记界面,默认是permit All
		.and()
		.authorizeRequests().antMatchers("/","/home").permitAll() //不用身份认证可以访问
		.and()
		.authorizeRequests().anyRequest().authenticated() //其它的请求要求必须有身份认证
        .and()
        .csrf() //防止CSRF(跨站请求伪造)配置
        .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable();
    }

	@Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

配置用户信息,保存在内存中。也可以自定义将用户数据保存在数据库中,实现UserDetailsService接口,进行认证与授权,略。

配置访问哪些URL需要授权。必须配置authorizeRequests(),否则启动报错,说是没有启用security技术。

注意,在这里的身份进行认证与授权没有涉及到OAuth的技术:

当访问要授权的URL时,请求会被DelegatingFilterProxy拦截,如果还没有授权,请求就会被重定向到登录界面。在登录成功(身份认证并授权)后,请求被重定向至之前访问的URL。

2、OAuth2的授权服务:

主要作用是OAuth2的客户端进行认证与授权。

package com.banling.oauth2server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter{

	@Autowired
	private TokenStore tokenStore;

	@Autowired
    private AuthenticationManager authenticationManager;

	@Autowired
	private ApprovalStore approvalStore;

	@Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //添加客户端信息
        //使用内存存储OAuth客户端信息
        clients.inMemory()
                // client_id
                .withClient("client")
                // client_secret
                .secret("secret")
                // 该client允许的授权类型,不同的类型,则获得token的方式不一样。
                .authorizedGrantTypes("authorization_code","implicit","refresh_token")
                .resourceIds("resourceId")
                //回调uri,在authorization_code与implicit授权方式时,用以接收服务器的返回信息
                .redirectUris("http://localhost:8090/")
                // 允许的授权范围
                .scopes("app","test");
    }

	@Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		//reuseRefreshTokens设置为false时,每次通过refresh_token获得access_token时,也会刷新refresh_token;也就是说,会返回全新的access_token与refresh_token。
		//默认值是true,只返回新的access_token,refresh_token不变。
        endpoints.tokenStore(tokenStore).approvalStore(approvalStore).reuseRefreshTokens(false)
                .authenticationManager(authenticationManager);
    }

	@Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.realm("OAuth2-Sample")
        	.allowFormAuthenticationForClients()
        	.tokenKeyAccess("permitAll()")
        	.checkTokenAccess("isAuthenticated()");
    }

	@Bean
	public TokenStore tokenStore() {
		//token保存在内存中(也可以保存在数据库、Redis中)。
		//如果保存在中间件(数据库、Redis),那么资源服务器与认证服务器可以不在同一个工程中。
		//注意:如果不保存access_token,则没法通过access_token取得用户信息
		return new InMemoryTokenStore();
	}

	@Bean
	public ApprovalStore approvalStore() throws Exception {
		TokenApprovalStore store = new TokenApprovalStore();
		store.setTokenStore(tokenStore);
		return store;
	}
}

配置OAuth2的客户端信息:clientId、client_secret、authorization_type、redirect_url等。本例是将数据保存在内存中。也可以保存在数据库中,实现ClientDetailsService接口,进行认证与授权,略。

TokenStore是access_token的存储单元,可以保存在内存、数据库、Redis中。本例是保存在内存中。

3、OAuth2的资源服务:

主要作用是配置资源受保护的OAuth2策略。

package com.banling.oauth2server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
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.security.oauth2.provider.token.TokenStore;
@Configuration
@EnableResourceServer
public class ResServerConfig extends ResourceServerConfigurerAdapter{

	@Autowired
	private TokenStore tokenStore;

	@Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .tokenStore(tokenStore)
                .resourceId("resourceId");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
    	/*
    	 注意:
    	 1、必须先加上: .requestMatchers().antMatchers(...),表示对资源进行保护,也就是说,在访问前要进行OAuth认证。
    	 2、接着:访问受保护的资源时,要具有哪里权限。
    	 ------------------------------------
    	 否则,请求只是被Security的拦截器拦截,请求根本到不了OAuth2的拦截器。
    	 同时,还要注意先配置:security.oauth2.resource.filter-order=3,否则通过access_token取不到用户信息。
    	 ------------------------------------
    	 requestMatchers()部分说明:
    	 Invoking requestMatchers() will not override previous invocations of ::
    	 mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher).
    	 */

        http
        	// Since we want the protected resources to be accessible in the UI as well we need
			// session creation to be allowed (it's disabled by default in 2.0.6)
        	//另外,如果不设置,那么在通过浏览器访问被保护的任何资源时,每次是不同的SessionID,并且将每次请求的历史都记录在OAuth2Authentication的details的中
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
			.and()
       		.requestMatchers()
           .antMatchers("/user","/res/**")
           .and()
           .authorizeRequests()
           .antMatchers("/user","/res/**")
           .authenticated();
    }
}

配置哪些URL资源是受OAuth2保护的。注意,必须配置sessionManagement(),否则访问受护资源请求不会被OAuth2的拦截器ClientCredentialsTokenEndpointFilter与OAuth2AuthenticationProcessingFilter拦截,也就是说,没有配置的话,资源没有受到OAuth2的保护。

4、受OAuth2保存的资源:

1)获取OAuth2客户端的信息

package com.banling.oauth2server.web;
import java.security.Principal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

	@RequestMapping("/user")
	public Principal user(Principal principal) {
		//principal在经过security拦截后,是org.springframework.security.authentication.UsernamePasswordAuthenticationToken
		//在经OAuth2拦截后,是OAuth2Authentication
	    return principal;
	}
}

2)其它受保护的资源

package com.banling.oauth2server.web;
import java.security.Principal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 作为OAuth2的资源服务时,不能在Controller(或者RestController)注解上写上URL,因为这样不会被识别,会报404错误。<br>
 *<br> {
 *<br>     "timestamp": 1544580859138,
 *<br>     "status": 404,
 *<br>     "error": "Not Found",
 *<br>     "message": "No message available",
 *<br>     "path": "/res/getMsg"
 *<br> }
 *<br>
 *
 *
 */
@RestController()//作为资源服务时,不能带上url,@RestController("/res")是错的,无法识别。只能在方法上注解全路径
public class ResController {

	@RequestMapping("/res/getMsg")
	public String getMsg(String msg,Principal principal) {//principal中封装了客户端(用户,也就是clientDetails,区别于Security的UserDetails,其实clientDetails中也封装了UserDetails),不是必须的参数,除非你想得到用户信息,才加上principal。
		return "Get the msg: "+msg;
	}
}

5、application.properties配置:

security.oauth2.resource.filter-order=3 必须配置,否则对受护资源请求不会被OAuth2的拦截器拦截。

6、测试

1)authorization_code方式获取code,然后再通过code获取access_token(和refresh_token)。

在浏览输入:

http://localhost:8080/oauth/authorize?client_id=client&response_type=code&redirect_uri=http://localhost:8090/

在登录界面输入用户名与密码user/user,提交。

提交后服务重定向 至scope的授权界面:

授权后,在回调uri中可以得从code:

用postman工具,设置header的值,通过code获取access_token与fresh_token:

2)implict方式接获取access_token。

浏览器中输入:

http://localhost:8080/oauth/authorize?client_id=client&response_type=token&redirect_uri=http://localhost:8090/

可以直接获得access_token。

3)通过refresh_token获取access_token与refresh_token。

用postman工具测试,根据refresh_token获取新的access_token与fresh_token。

4)获取OAuth2客户端的信息。

可以通过get方式,也可以通过设置header获取。

get方式,看url字符串:

设置header的方式:

5)访问其它受保护的资源

github上的源码: https://github.com/banat020/OAuth2-server

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • springboot2.x实现oauth2授权码登陆的方法

    一 进行授权页 浏览器输入 http://localhost:8081/oauth/authorize?response_type=code&redirect_uri=http://localhost:8081/callback&client_id=android1&scop=all 二 使用资源站用户登陆 自动跨到资源登陆页,先登陆 三 授权资源类型 登陆成功后,去授权你的资源,这些资源是在AuthorizationServerConfig.configure方法里配置的 @Ov

  • 详解Springboot Oauth2 Server搭建Oauth2认证服务

    本教程源码 https://github.com/bestaone/HiAuth 源码比较全面,教程我就只介绍关键代码了,喜欢的点个star,谢谢! 关键词 微服务认证 Oauth2 认证中心 springboot spring-cloud-starter-oauth2 集成Oauth2 Oauth2 客户端 介绍 这里我将介绍两个部分 Oauth2 server 的开发 (hi-auth-web模块) Oauth2 client 的开发 (hi-mall-web模块) 效果图 himall.g

  • Spring Security OAuth2认证授权示例详解

    本文介绍了如何使用Spring Security OAuth2构建一个授权服务器来验证用户身份以提供access_token,并使用这个access_token来从资源服务器请求数据. 1.概述 OAuth2是一种授权方法,用于通过HTTP协议提供对受保护资源的访问.首先,OAuth2使第三方应用程序能够获得对HTTP服务的有限访问权限,然后通过资源所有者和HTTP服务之间的批准交互来让第三方应用程序代表资源所有者获取访问权限. 1.1 角色 OAuth定义了四个角色 资源所有者 - 应用程序的

  • Spring Cloud下基于OAUTH2认证授权的实现示例

    在Spring Cloud需要使用OAUTH2来实现多个微服务的统一认证授权,通过向OAUTH服务发送某个类型的grant type进行集中认证和授权,从而获得access_token,而这个token是受其他微服务信任的,我们在后续的访问可以通过access_token来进行,从而实现了微服务的统一认证授权. 本示例提供了四大部分: discovery-service:服务注册和发现的基本模块 auth-server:OAUTH2认证授权中心 order-service:普通微服务,用来验证认

  • Springboot开发OAuth2认证授权与资源服务器操作

    设计并开发一个开放平台. 一.设计: 网关可以 与认证授权服务合在一起,也可以分开. 二.开发与实现: 用Oauth2技术对访问受保护的资源的客户端进行认证与授权. Oauth2技术应用的关键是: 1)服务器对OAuth2客户端进行认证与授权. 2)Token的发放. 3)通过access_token访问受OAuth2保护的资源. 选用的关键技术:Springboot, Spring-security, Spring-security-oauth2. 提供一个简化版,用户.token数据保存在内

  • springboot使用CommandLineRunner解决项目启动时初始化资源的操作

    前言: 在我们实际工作中,总会遇到这样需求,在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等. 今天就给大家介绍一个 Spring Boot 神器,专门帮助大家解决项目启动初始化资源操作. 这个神器就是 CommandLineRunner,CommandLineRunner 接口的 Component 会在所有 Spring Beans 都初始化之后,SpringApplication.run() 之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作. 正文

  • nodejs实现OAuth2.0授权服务认证

    OAuth是一种开发授权的网络标准,全拼为open authorization,即开放式授权,最新的协议版本是2.0. 举个栗子: 有一个"云冲印"的网站,可以将用户储存在Google的照片,冲印出来.用户为了使用该服务,必须让"云冲印"读取自己储存在Google上的照片. 传统方法是,用户将自己的Google用户名和密码,告诉"云冲印",后者就可以读取用户的照片了.这样的做法有以下几个严重的缺点. "云冲印"为了后续的服务,

  • 基于SpringBoot整合oauth2实现token认证

    这篇文章主要介绍了基于SpringBoot整合oauth2实现token 认证,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 session和token的区别: session是空间换时间,而token是时间换空间.session占用空间,但是可以管理过期时间,token管理部了过期时间,但是不占用空间. sessionId失效问题和token内包含. session基于cookie,app请求并没有cookie . token更加安全(每次请

  • Node.js开发静态资源服务器

    目录 正文 静态资源服务器 模块化 最后 正文 在09年Node.js出来后,让前端开发人员的开发路线变的不再那么单调,经过这么多年的发展,我们的开发基本已经离不开Node.js,不管是用作于工具类的开发,还是做完服务端的中间层,Node.js都占据了非常重要的地位,今天我们就一起通过原生的js+Node来实现一个简单的静态资源服务,如果你还不了解这方面的知识,那就跟我一起来学习吧! 静态资源服务器 Node.js经过这么多年的发展,已经有了很多很优秀的基础框架或类库,像express.js.K

  • Springboot shiro认证授权实现原理及实例

    关于认证授权,需要的数据表有:用户表,角色表,用户角色关联表,权限表,角色权限关联表,一次如下 之前写过了shiro的登录认证,在自定义的realm中,我们实现AuthorizingRealm接口中的方法:package com.zs.springboot.realm; import com.zs.springboot.model.User; import com.zs.springboot.service.UserService; import com.zs.springboot.util.R

  • 使用Springboot搭建OAuth2.0 Server的方法示例

    OAuth是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是2.0版. 本文对OAuth 2.0的设计思路和运行流程,做一个简明通俗的解释,主要参考材料为RFC 6749. OAuth 简介 OAuth 是由 Blaine Cook.Chris Messina.Larry Halff 及 David Recordon 共同发起的,目的在于为 API 访问授权提供一个安全.开放的标准. 基于 OAuth 认证授权具有以下特点: 安全.OAuth 与别的授

  • Android开发:微信授权登录与微信分享完全解析

    前言 在移动互联网浪潮中,联网APP已经把单机拍死在沙滩上,很多公司都希望自家应用能够有一套帐号系统,可是许多用户却并不一定买账:我凭啥注册你家应用的帐号?微博,微信,QQ几乎成了每个人手机中的必装应用,于是微信,微博,QQ说了:来来来,你们都可以用我家的帐号登录你家应用,只要你遵循OAuth2.0协议标准就行.于是第三方社交帐号登陆成为了许多新兴应用的选择,由于腾讯官方微信开放平台的在线文档相对最新的SDK有些出入,并且登录相关的文档结构次序有些紊乱,今天就把我的一些经验记录在此,对微信开放平

随机推荐