1.简介

在本教程中,我们将研究如何使用Spring Security和OAuth来基于路径模式( / api / ** )保护服务器上的管理资源。 我们配置的另一个路径模式( / oauth / token )将帮助已配置的授权服务器生成访问令牌。 请注意,我们将在此演示应用程序中使用“ 密码授予类型”

在继续实施之前,让我们回顾一下与该授予类型有关的事件。

2.资源所有者密码凭证授予类型

  • 在受信任的应用程序之间使用。
  • 用户(资源所有者)直接与客户端应用程序共享凭据,客户端应用程序在成功验证用户凭据并进一步授权用户访问服务器上的有限资源后,请求授权服务器返回访问令牌。

有用的链接

  • 了解有关其他授权授予类型的更多信息
  • 了解OAuth2令牌认证

3.实施

确保将所需的pom条目正确添加到pom.xml文件中。

pom.xml

<!-- Spring dependencies -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${springframework.version}</version>
</dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${springframework.version}</version>
</dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${springframework.version}</version>
</dependency><!-- Spring Security Dependencies -->
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-core</artifactId><version>${spring-security.version}</version>
</dependency>
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId><version>${spring-security.version}</version>
</dependency>
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>${spring-security.version}</version>
</dependency>
<dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>${spring-security.oauth.version}</version>
</dependency>

web.xml

更新web.xml文件以加载上下文文件并配置Spring Security过滤器,该过滤器将在处理请求之前重定向身份验证和授权请求。

<web-app xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0"><display-name>Archetype Created Web Application</display-name><servlet><servlet-name>mvc-dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>mvc-dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- Loads context files --><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/mvc-dispatcher-servlet.xml,/WEB-INF/spring-security.xml</param-value></context-param><!-- Spring Security --><filter><filter-name>springSecurityFilterChain</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping><filter-name>springSecurityFilterChain</filter-name><url-pattern>/*</url-pattern></filter-mapping>
</web-app>

mvc-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"><context:component-scan base-package="com.jcombat" /><mvc:annotation-driven /><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix"><value>/WEB-INF/pages/</value></property><property name="suffix"><value>.jsp</value></property></bean>
</beans>

由于我们将使用admin JSP文件,因此我们已经为其配置了相应的视图解析器。

现在,让我们在其上下文文件中配置Spring Security OAuth。

spring-security.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"xmlns:context="http://www.springframework.org/schema/context"xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "><!-- Default url to get a token from OAuth --><http pattern="/oauth/token" create-session="stateless"authentication-manager-ref="clientAuthenticationManager"xmlns="http://www.springframework.org/schema/security"><intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" /><anonymous enabled="false" /><http-basic entry-point-ref="clientAuthenticationEntryPoint" /><custom-filter ref="clientCredentialsTokenEndpointFilter"after="BASIC_AUTH_FILTER" /><access-denied-handler ref="oauthAccessDeniedHandler" /></http><!-- URLs should be protected and what roles have access to them --><!-- Can define more patterns based on the protected resources hosted on the server --><http pattern="/api/**" create-session="never"entry-point-ref="oauthAuthenticationEntryPoint"access-decision-manager-ref="accessDecisionManager"xmlns="http://www.springframework.org/schema/security"><anonymous enabled="false" /><intercept-url pattern="/api/**" access="ROLE_APP" /><!-- Protect oauth clients with resource ids --><custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /><access-denied-handler ref="oauthAccessDeniedHandler" /></http><bean id="oauthAuthenticationEntryPoint"class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"><property name="realmName" value="demo/client" /></bean><bean id="clientAuthenticationEntryPoint"class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"><property name="realmName" value="demo/client" /><property name="typeName" value="Basic" /></bean><bean id="oauthAccessDeniedHandler"class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /><bean id="clientCredentialsTokenEndpointFilter"class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"><property name="authenticationManager" ref="clientAuthenticationManager" /></bean><bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"xmlns="http://www.springframework.org/schema/beans"><constructor-arg><list><bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" /><bean class="org.springframework.security.access.vote.RoleVoter" /><bean class="org.springframework.security.access.vote.AuthenticatedVoter" /></list></constructor-arg></bean><authentication-manager id="clientAuthenticationManager"xmlns="http://www.springframework.org/schema/security"><authentication-provider user-service-ref="clientDetailsUserService" /></authentication-manager><!-- This is simple authentication manager, with a hard-coded username/password combination. We can replace this with a user defined service to fetch user credentials from DB instead --><authentication-manager alias="authenticationManager"xmlns="http://www.springframework.org/schema/security"><authentication-provider><user-service><user name="admin" password="123" authorities="ROLE_APP" /></user-service></authentication-provider></authentication-manager><bean id="clientDetailsUserService"class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService"><constructor-arg ref="clientDetails" /></bean><!-- This defines the token store. We have currently used in-memory token store but we can instead use a user defined one --><bean id="tokenStore"class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" /><!-- If need to store tokens in DB <bean id="tokenStore"class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore"><constructor-arg ref="jdbcTemplate" /></bean> --><!-- This is where we defined token based configurations, token validity and other things --><bean id="tokenServices"class="org.springframework.security.oauth2.provider.token.DefaultTokenServices"><property name="tokenStore" ref="tokenStore" /><property name="supportRefreshToken" value="true" /><property name="accessTokenValiditySeconds" value="120" /><property name="clientDetailsService" ref="clientDetails" /></bean><bean id="userApprovalHandler"class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler"><property name="tokenServices" ref="tokenServices" /></bean><!-- The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization --><oauth:authorization-serverclient-details-service-ref="clientDetails" token-services-ref="tokenServices"user-approval-handler-ref="userApprovalHandler"><oauth:authorization-code /><oauth:implicit /><oauth:refresh-token /><oauth:client-credentials /><oauth:password /></oauth:authorization-server><!-- Define protected resources hosted by the resource server --><oauth:resource-server id="resourceServerFilter"resource-id="adminProfile" token-services-ref="tokenServices" /><!-- OAuth clients allowed to access the protected resources, can be something like facebook, google if we are sharing any resource with them --><oauth:client-details-service id="clientDetails"><oauth:client client-id="fbApp"authorized-grant-types="password,refresh_token"secret="fbApp" authorities="ROLE_APP" resource-ids="adminProfile" /></oauth:client-details-service><sec:global-method-securitypre-post-annotations="enabled" proxy-target-class="true"><sec:expression-handler ref="oauthExpressionHandler" /></sec:global-method-security><oauth:expression-handler id="oauthExpressionHandler" /><oauth:web-expression-handler id="oauthWebExpressionHandler" /></beans>

我们已经配置了/ oauth / token URL来发布访问和刷新令牌,并且/ api / **映射到服务器上实际受保护的资源。 因此,要访问与模式/ api / **匹配的任何URL,需要将有效令牌与请求一起传递。

身份验证管理器是进行身份验证的容器。 在我们的情况下,身份验证管理器检查–

  • 用户是否通过身份验证。
  • 用户是否请求了正确的客户ID。
  • 如果client-id正确,则该用户是否有权使用它来访问服务器上的管理配置文件。

请参阅以下代码段–

<authentication-manager id="clientAuthenticationManager"xmlns="http://www.springframework.org/schema/security"><authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager><bean id="clientDetailsUserService"class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService"><constructor-arg ref="clientDetails" />
</bean><!-- OAuth clients allowed to access the protected resources, can be something like facebook, google if we are sharing any resource with them -->
<oauth:client-details-service id="clientDetails"><oauth:client client-id="fbApp"authorized-grant-types="password,refresh_token"secret="fbApp" authorities="ROLE_APP" resource-ids="adminProfile" />
</oauth:client-details-service>

用户通过身份验证后, 授权服务器将调用tokenServices并颁发访问令牌。

<oauth:authorization-serverclient-details-service-ref="clientDetails" token-services-ref="tokenServices"user-approval-handler-ref="userApprovalHandler"><oauth:authorization-code /><oauth:implicit /><oauth:refresh-token /><oauth:client-credentials /><oauth:password />
</oauth:authorization-server><bean id="tokenServices"class="org.springframework.security.oauth2.provider.token.DefaultTokenServices"><property name="tokenStore" ref="tokenStore" /><property name="supportRefreshToken" value="true" /><property name="accessTokenValiditySeconds" value="120" /><property name="clientDetailsService" ref="clientDetails" />
</bean><bean id="tokenStore"class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" /><bean id="userApprovalHandler"class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler"><property name="tokenServices" ref="tokenServices" />
</bean>

在指定客户端时,请注意我们指定的授权类型,即password

<oauth:client-details-service id="clientDetails"><oauth:client client-id="fbApp"authorized-grant-types="password,refresh_token"secret="fbApp" authorities="ROLE_APP" resource-ids="adminProfile" />
</oauth:client-details-service>

发出访问令牌后,我们便可以访问服务器上受保护的资源,并将其与每个请求一起传递。 最后,让我们看看我们编写的Spring Controller –

DemoController.java

package com.jcombat.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class DemoController {@RequestMapping("/api/admin")public String getAdminPage() {return "/secured/admin";}
}

4.运行应用程序

要运行该应用程序,让我们首先从授权服务器请求访问令牌-

http:// localhost:8080 / SpringSecurityOAuth / oauth / token? grant_type =密码和client_id = fbApp& client_secret = fbApp& 用户名 = admin& 密码 = 123

{  "access_token":"5c0c1a28-9603-4818-9ebb-6014600c3de9","token_type":"bearer","refresh_token":"ada8a736-3082-4c3d-9cbf-f043ab8f415f","expires_in":119
}

生成访问令牌后,我们准备将其与服务器上对受保护资源的所有后续请求一起传递。

http:// localhost:8080 / SpringSecurityOAuth / api / admin? access_token = 5c0c1a28-9603-4818-9ebb-6014600c3de9

5.下载代码

下载源代码

翻译自: https://www.javacodegeeks.com/2017/09/securing-resources-using-spring-security-oauth.html

使用带有OAuth的Spring Security保护资源相关推荐

  1. 使用Spring Security保护REST服务

    总览 最近,我正在一个使用REST服务层与客户端应用程序(GWT应用程序)进行通信的项目中. 因此,我花了很多时间来弄清楚如何使用Spring Security保护REST服务. 本文介绍了我找到的解 ...

  2. tomcat使用ssl_使用SSL和Spring Security保护Tomcat应用程序的安全

    tomcat使用ssl 如果您看过我的上一个博客,您会知道我列出了Spring Security可以做的十件事 . 但是,在开始认真使用Spring Security之前,您真正要做的第一件事就是确保 ...

  3. 使用SSL和Spring Security保护Tomcat应用程序的安全

    如果您看过我的上一个博客,您会知道我列出了Spring Security可以做的十件事 . 但是,在认真开始使用Spring Security之前,您真正要做的第一件事就是确保您的Web应用使用正确的 ...

  4. Spring Boot集成Ueditor富文本编辑器,实现图片上传,视频上传,返回内容功能并且通过OSS转换为链接并且解决Spring Security静态资源访问以及跨域问题

    学习自https://cloud.tencent.com/developer/article/1452451 现在是晚上22点,刚刚和我们的前端交流完了富文本编辑器的一些意见和看法 还是老样子 需求 ...

  5. OAuth与Spring Security

    摘自Wikipedia: OAuth ( 开放式身份验证 )是一种开放式身份验证标准. 它允许用户与其他站点共享存储在一个站点上的私有资源(例如照片,视频,联系人列表),而不必发出其凭据(通常是用户名 ...

  6. gwt格式_使用Spring Security保护GWT应用程序的安全

    gwt格式 在本教程中,我们将看到如何将GWT与Spring的安全模块(即Spring Security)集成. 我们将看到如何保护GWT入口点,如何检索用户的凭据以及如何记录各种身份验证事件. 此外 ...

  7. 使用Spring Security保护GWT应用程序

    在本教程中,我们将看到如何将GWT与Spring的安全模块(即Spring Security)集成在一起. 我们将看到如何保护GWT入口点,如何检索用户的凭据以及如何记录各种身份验证事件. 此外,我们 ...

  8. Spring Security 自定义资源服务器实践

    相关文章: OAuth2的定义和运行流程 Spring Security OAuth实现Gitee快捷登录 Spring Security OAuth实现GitHub快捷登录 Spring Secur ...

  9. 使用JWT和Spring Security保护REST API

    通常情况下,把API直接暴露出去是风险很大的,不说别的,直接被机器攻击就喝一壶的.那么一般来说,对API要划分出一定的权限级别,然后做一个用户的鉴权,依据鉴权结果给予用户开放对应的API.目前,比较主 ...

最新文章

  1. 天天Linux-安装samba,nasm
  2. boost::outcome_v2::std_result用法的测试程序
  3. C语言实现上三角蛇形矩阵不用数组,蛇形矩阵c语言实现
  4. Node.js进程管理之Process模块
  5. python sns绘制回归线_Python数分实战:员工流失情况预测
  6. 【Spring】Could not commit JPA transaction RollbackException: Transaction marked as rollbackOnly
  7. java程序编辑器_java实现编辑器(一)
  8. tomcat登录账户配置
  9. 中国电信物联网正式平台设置订阅地址
  10. 佰马科技参加第16届中国道路照明论坛,助力智慧灯杆建设
  11. 5、JSP面试题总结
  12. 国内装备制造业为什么需要项目管理
  13. App项目实战之路(三):原型篇
  14. 阿里java社招_社招|阿里巴巴Java工程师社招凉经
  15. 从键盘输入一个整数,判断它是正数,负数,0
  16. IDEA太强悍了!java导出excel合并单元格边框设置
  17. 如何在Python中安装NumPy
  18. 电脑一启动吃鸡就重启计算机,租号器登录电脑重启-租号玩绝地求生提示登录出现异请重启客户端...
  19. C/C++黑魔法-利用include宏读文件
  20. 你要整合资源,首先你得是一个有资源的人

热门文章

  1. SpringBoot2.1.9 Mybatis由于@Mapper注解多数据源配置不生效问题
  2. 汇编语言(二十三)之求一个数的补数
  3. 以吃货的角度理解 IaaS,PaaS,SaaS 是什么
  4. 消费端整合SpringCloudGateway
  5. JS生成x到y的随机数
  6. 利用赫夫曼编码进行数据解压
  7. 微信消息提醒与消息数字提示之BadgeView
  8. 气泡提示效果css.html,用纯CSS3绘制高端简约的气泡提示框
  9. mysql循环insert多条数据
  10. 系统架构师5 ***********那就给个合格分了。111