很多人在进行项目开发时都会用到Oauth2.0结合SpringSecurity或者Shiro进行权限拦截以及用户验证,网上也有很多的案例,前几天项目里边需要用到,顺便整合了进来,特此写篇博客,记录下过程。

项目结构如下:

首先准备pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.xz.springcloud</groupId>
<artifactId>f-oauth2-pwd-mode</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>f-oauth2-pwd-mode</name>
<description>Demo project for Spring Boot</description> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<oauth.version>2.3.3.RELEASE</oauth.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.2.1.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> </dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

MyUserDetailService.java

package com.oauth.config;

import java.util.ArrayList;
import java.util.List; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component; /**
*
* @author yuxuan
*
*/
@Component
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO 这个地方可以通过username从数据库获取正确的用户信息,包括密码和权限等。
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
return new User(username, "{noop}123456", grantedAuthorityList);
}
}

OAuth2ServerConfig.java

package com.oauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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; @Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter { @Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()") //url:/oauth/token_key,exposes public key for token verification if using JWT tokens
.checkTokenAccess("isAuthenticated()") //url:/oauth/check_token allow check token
.allowFormAuthenticationForClients();
} /**
* 注入authenticationManager
* 来支持 password grant type
*/
@Autowired
private AuthenticationManager authenticationManager; @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
} @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret("{noop}secret")
.authorizedGrantTypes("client_credentials", "password", "refresh_token")
.scopes("all")
.resourceIds("resourcesId")
.accessTokenValiditySeconds(1200)
.refreshTokenValiditySeconds(50000);
} }

ResourceServerConfig.java

package com.oauth.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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; @Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/api/**").and().authorizeRequests().antMatchers("/api/**").authenticated();
} @Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("resourcesId").stateless(true);
} }

WebConfig.java

package com.oauth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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; @EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class WebConfig extends WebSecurityConfigurerAdapter { @Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.requestMatchers().antMatchers("/oauth/**")
.and()
.authorizeRequests()
.antMatchers("/oauth/**").authenticated();
} /**
* 需要配置这个支持password模式 support password grant type
* @return
* @throws Exception
*/
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
} }

IndexCtrl.java

package com.oauth.ctrl;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class IndexCtrl { @GetMapping("hello")
public String hello() {
return "Hello World";
} @GetMapping("api/hello")
public String apiHello() {
return "Hello World";
} }

App.java

package com.oauth;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class App { public static void main(String[] args) {
SpringApplication.run(App.class, args); }
}

以上就是一个代码的配置,下面启动App类,运行main函数。项目启动完成后用rest client访问hello接口

可以看到提示无效的token,接下我们请求获取token。利用CURL命令请求如下:

curl -i -X POST -d "username=admin&password=123456&grant_type=password&client_id=client&client_secret=secret" http://localhost:8888/oauth/token

可以看到,至此已经访问成功了。

也可以利用GET方式直接访问,如下:

http://localhost:8888/api/hello?access_token=cca911c0-532f-475b-83e6-3a2671a8fe07

有问题可以在下面评论,技术问题可以私聊我。

SpringBoot2.x版本整合SpringSecurity、Oauth2进行password认证的更多相关文章

  1. springboot2.x版本整合redis(单机/集群)(使用lettuce)

    在springboot1.x系列中,其中使用的是jedis,但是到了springboot2.x其中使用的是Lettuce. 此处springboot2.x,所以使用的是Lettuce.关于jedis跟 ...

  2. SpringBoot2.0整合SpringSecurity实现WEB JWT认证

    相信很多做技术的朋友都做过前后端分离项目,项目分离后认证就靠JWT,费话不多说,直接上干活(写的不好还请多多见谅,大牛请绕行) 直接上代码,项目为Maven项目,结构如图: 包分类如下: com.ap ...

  3. SpringBoot整合Thymeleaf-基于SpringBoot2.X版本

    1.为啥要用Thymeleaf模板引擎?现在不都前后端分离了么? 熊dei们,别着急,我们先来谈谈为啥开始用Thymeleaf模板引擎,先照顾照顾下我们这些可爱的小白童鞋.... 为啥开始用Thyme ...

  4. 使用Spring Security Oauth2完成RESTful服务password认证的过程

            摘要:Spring Security与Oauth2整合步骤中详细描述了使用过程,但它对于入门者有些重量级,比如将用户信息.ClientDetails.token存入数据库而非内存.配置 ...

  5. 厉害!我带的实习生仅用四步就整合好SpringSecurity+JWT实现登录认证!

    小二是新来的实习生,作为技术 leader,我还是很负责任的,有什么锅都想甩给他,啊,不,一不小心怎么把心里话全说出来了呢?重来! 小二是新来的实习生,作为技术 leader,我还是很负责任的,有什么 ...

  6. Springboot2+SpringSecurity+Oauth2+Mysql数据库实现持久化客户端数据

    目录 介绍 建表,初始化数据 工程配置 Authorization Server - Spring Security配置 Authorization Server - 授权服务器 Resource S ...

  7. java框架之SpringBoot(15)-安全及整合SpringSecurity

    SpringSecurity介绍 Spring Security 是针对 Spring 项目的安全框架,也是 Spring Boot 底层安全模块默认的技术选型.它可以实现强大的 Web 安全控制.对 ...

  8. springboot2.1.7整合mybati3.5.2与mysql8.0.13

    springboot2.x已经发布一段时间,博主在这里使用springboot2.1.7整合mybatis3.5.2,使用的数据库为mysql8.0.13 1. 导入依赖 <!--mysql-- ...

  9. SpringBoot:整合SpringSecurity

    目录 SpringSecurity(安全) 搭建环境 使用 用户认证和授权 注销及权限控制 记住我及登录页面定制 SpringBoot 整合 SpringSecurity: 用户认证和授权.注销及权限 ...

随机推荐

  1. [K/3Cloud] 在设计时复制已有表单菜单或菜单项快速建立菜单

    1.打开已有表单XML,找到FormAppearance的Menu节点,按Ctrl+C复制 <Appearances> <FormAppearance ElementType=&qu ...

  2. 【Tomcat】Tomcat Connector的三种运行模式【bio、nio、apr】

    Tomcat Connector(Tomcat连接器)有bio.nio.apr三种运行模式 bio bio(blocking I/O,阻塞式I/O操作),表示Tomcat使用的是传统的Java I/O ...

  3. 移动端click事件延迟300ms该如何解决

    window.addEventListener( "load", function() {     FastClick.attach( document.body ); }, fa ...

  4. 通过setContentView设置activity的不同样式

    public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle saved ...

  5. Python基础之 一 字典(dict)

    字典:是一种key - value的数据类型.语法:info = { key:value }特性:无序,key必须唯一(所以天生去重) 方法如下:del dict[key]:删除字典指定键len(di ...

  6. Being a Good Boy in Spring Festival 博弈论 Nim博弈

    易游戏雷火盘古校园招聘开始! kiki's game Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 40000/10000 K (Ja ...

  7. zoj3988 Prime Set

    思路不难想到二分图求个最大匹配P,若P>=K,则2*K即可,否则应为P*2+min(K-P,未匹配且有度数不为0的顶点个数s).但坑点在于有1的情况,所以如果直接建二分图去跑最大匹配会因为1的影 ...

  8. [bzoj2150]部落战争_二分图最小路径覆盖

    部落战争 bzoj-2150 题目大意:题目链接. 注释:略. 想法: 显然是最小路径覆盖,我们知道:二分图最小路径覆盖等于节点总数-最大匹配. 所以我们用匈牙利或者dinic跑出最大匹配,然后用总结 ...

  9. MongoDB小结22 - id生成规则

    MongoDB的文档必须有一个_id键. 目的是为了确认在集合里的每个文档都能被唯一标识. ObjectId 是 _id 的默认类型. ObjectId 采用12字节的存储空间,每个字节两位16进制数 ...

  10. C#中使用 Oracle的事务与存储过程

    1 存储过程 1.1 不带参数,没有返回值 创建表 create table test (ID number, NAME varchar2(), SEX varchar2(), AGE number, ...