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

项目结构如下:

首先准备pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.0.3.RELEASE</version>
  9. <relativePath /> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.xz.springcloud</groupId>
  12. <artifactId>f-oauth2-pwd-mode</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>f-oauth2-pwd-mode</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  19. <java.version>1.8</java.version>
  20. <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
  21. <oauth.version>2.3.3.RELEASE</oauth.version>
  22. </properties>
  23. <dependencies>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.security.oauth</groupId>
  30. <artifactId>spring-security-oauth2</artifactId>
  31. <version>2.2.1.RELEASE</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-security</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-test</artifactId>
  40. <scope>test</scope>
  41. </dependency>
  42. </dependencies>
  43. <dependencyManagement>
  44. <dependencies>
  45. <dependency>
  46. <groupId>org.springframework.cloud</groupId>
  47. <artifactId>spring-cloud-dependencies</artifactId>
  48. <version>${spring-cloud.version}</version>
  49. <type>pom</type>
  50. <scope>import</scope>
  51. </dependency>
  52. </dependencies>
  53. </dependencyManagement>
  54. <build>
  55. <plugins>
  56. <plugin>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-maven-plugin</artifactId>
  59. </plugin>
  60. </plugins>
  61. </build>
  62. </project>

MyUserDetailService.java

  1. package com.oauth.config;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.springframework.security.core.GrantedAuthority;
  5. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  6. import org.springframework.security.core.userdetails.User;
  7. import org.springframework.security.core.userdetails.UserDetails;
  8. import org.springframework.security.core.userdetails.UserDetailsService;
  9. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  10. import org.springframework.stereotype.Component;
  11. /**
  12. *
  13. * @author yuxuan
  14. *
  15. */
  16. @Component
  17. public class MyUserDetailsService implements UserDetailsService {
  18. @Override
  19. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  20. // TODO 这个地方可以通过username从数据库获取正确的用户信息,包括密码和权限等。
  21. List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
  22. grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
  23. grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
  24. return new User(username, "{noop}123456", grantedAuthorityList);
  25. }
  26. }

OAuth2ServerConfig.java

  1. package com.oauth.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.http.HttpMethod;
  5. import org.springframework.security.authentication.AuthenticationManager;
  6. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  7. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  8. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  9. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  10. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  11. @Configuration
  12. @EnableAuthorizationServer
  13. public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
  14. @Override
  15. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
  16. oauthServer
  17. .tokenKeyAccess("permitAll()") //url:/oauth/token_key,exposes public key for token verification if using JWT tokens
  18. .checkTokenAccess("isAuthenticated()") //url:/oauth/check_token allow check token
  19. .allowFormAuthenticationForClients();
  20. }
  21. /**
  22. * 注入authenticationManager
  23. * 来支持 password grant type
  24. */
  25. @Autowired
  26. private AuthenticationManager authenticationManager;
  27. @Override
  28. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  29. endpoints.authenticationManager(authenticationManager);
  30. endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
  31. }
  32. @Override
  33. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  34. clients.inMemory()
  35. .withClient("client")
  36. .secret("{noop}secret")
  37. .authorizedGrantTypes("client_credentials", "password", "refresh_token")
  38. .scopes("all")
  39. .resourceIds("resourcesId")
  40. .accessTokenValiditySeconds(1200)
  41. .refreshTokenValiditySeconds(50000);
  42. }
  43. }

ResourceServerConfig.java

  1. package com.oauth.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  4. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  5. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  6. import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
  7. @Configuration
  8. @EnableResourceServer
  9. public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  10. @Override
  11. public void configure(HttpSecurity http) throws Exception {
  12. http.requestMatchers().antMatchers("/api/**").and().authorizeRequests().antMatchers("/api/**").authenticated();
  13. }
  14. @Override
  15. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  16. resources.resourceId("resourcesId").stateless(true);
  17. }
  18. }

WebConfig.java

  1. package com.oauth.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.security.authentication.AuthenticationManager;
  4. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  5. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  6. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  8. @EnableWebSecurity
  9. @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
  10. public class WebConfig extends WebSecurityConfigurerAdapter {
  11. @Override
  12. protected void configure(HttpSecurity http) throws Exception {
  13. http.csrf().disable();
  14. http.requestMatchers().antMatchers("/oauth/**")
  15. .and()
  16. .authorizeRequests()
  17. .antMatchers("/oauth/**").authenticated();
  18. }
  19. /**
  20. * 需要配置这个支持password模式 support password grant type
  21. * @return
  22. * @throws Exception
  23. */
  24. @Override
  25. @Bean
  26. public AuthenticationManager authenticationManagerBean() throws Exception {
  27. return super.authenticationManagerBean();
  28. }
  29. }

IndexCtrl.java

  1. package com.oauth.ctrl;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. public class IndexCtrl {
  6. @GetMapping("hello")
  7. public String hello() {
  8. return "Hello World";
  9. }
  10. @GetMapping("api/hello")
  11. public String apiHello() {
  12. return "Hello World";
  13. }
  14. }

App.java

  1. package com.oauth;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class App {
  6. public static void main(String[] args) {
  7. SpringApplication.run(App.class, args);
  8. }
  9. }

以上就是一个代码的配置,下面启动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. xtu summer individual 3 F - Opening Portals

    Opening Portals Time Limit: 2000ms Memory Limit: 262144KB This problem will be judged on CodeForces. ...

  2. Window Pains(poj 2585)

    题意: 一个屏幕要同时打开9个窗口,每个窗口是2*2的矩阵,整个屏幕大小是9*9,每个窗口位置固定. 但是是否被激活(即完整显示出来)不确定. 给定屏幕状态,问是否可以实现显示. 分析:拓扑排序,把完 ...

  3. idea使用之maven中央仓库索引更新

    接着上篇,上篇是更新本地已有的索引,这样在编写pom文件的时候,可以自动提示,但如果我们能够把整个中央仓库的索引更新下来,那不是更方便啦. 打开settings-->Build,Executio ...

  4. Spring3.2+mybatis3.2+Struts2.3整合配置文件大全

    0.配置文件目录 1.Spring配置 applicationContext-dao.xml <?xml version="1.0" encoding="UTF-8 ...

  5. PHP 关键词

    PHP 关键词 TCP 传输层通信协议 面向连接的.可靠的.基于字节流的 建立链接需要三次握手 Socket(套接字) 一个工具,一个接口 封装了TCP/IP协议 建立长链接的基础 HTTP 一个应用 ...

  6. PHP上传文件限制修改

    php.ini里面查看如下行: upload_max_filesize post_max_size memory_limit

  7. Less Time, More profit 最大权闭合子图(最大流最小割)

    The city planners plan to build N plants in the city which has M shops. Each shop needs products fro ...

  8. [bzoj2208][Jsoi2010]连通数_bitset_传递闭包floyd

    连通数 bzoj-2208 Jsoi-2010 题目大意:给定一个n个节点的有向图,问每个节点可以到达的点的个数和. 注释:$1\le n\le 2000$. 想法:网上有好多tarjan+拓扑序dp ...

  9. SQL PATINDEX检索

    语法格式:PATINDEX ( '%pattern%' , expression ) 返回pattern字符串在表达式expression里第一次出现的位置,起始值从1开始算. pattern字符串在 ...

  10. hdu 5288 OO’s Sequence(2015 Multi-University Training Contest 1)

    OO's Sequence                                                          Time Limit: 4000/2000 MS (Jav ...