基于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(),否则启动报错,说

  • 6
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值