• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

springboot 搞代码 4年前 (2022-01-09) 34次浏览 已收录 0个评论
文章目录[隐藏]

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

一、设计:

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

二、开发与实现:

用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 Exceptio<strong style="color:transparent">来2源gaodaima#com搞(代@码&网</strong>n {
        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;
	}
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Springboot开发OAuth2认证授权与资源服务器操作

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址