网站建设哪便宜,长沙微信营销公司,wordpress登录页美化,网站建设网银开通1.简介 在本教程中#xff0c;我们将介绍如何将Spring Security与OAuth结合使用以保护REST服务。 在演示应用程序中#xff0c;可以使用路径模式#xff08; / api / ** #xff09;访问服务器上受保护的REST资源#xff0c;以便基于该路径的请求URL映射到不同的控制器方法… 1.简介 在本教程中我们将介绍如何将Spring Security与OAuth结合使用以保护REST服务。 在演示应用程序中可以使用路径模式 / api / ** 访问服务器上受保护的REST资源以便基于该路径的请求URL映射到不同的控制器方法。 这意味着 - 路径中没有 / api 的任何REST请求URL都将保持无效 因为这些URL与任何控制器映射都不匹配。 完成所需的OAuth2配置后任何不带令牌作为参数的REST请求URL都将是未授权的 。 我们配置的另一个路径模式 / oauth / token 将帮助已配置的授权服务器生成访问令牌。 请注意我们将在此演示应用程序中使用“ 密码授予类型” 。 在继续实施之前让我们回顾一下与该授予类型有关的事件。 2.资源所有者密码凭证授予类型 在受信任的应用程序之间使用。 用户资源所有者直接与客户端应用程序共享凭据客户端应用程序在成功验证用户凭据并进一步授权用户访问服务器上的有限资源后请求授权服务器返回访问令牌。 有用的链接 了解有关其他授权授予类型的更多信息 了解OAuth2令牌认证 3.实施 确保将所需的pom条目正确添加到pom.xml文件中。 pom.xml project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdorg.springframework.samples.service.service/groupIdartifactIdSecureRESTWithOAuth/artifactIdversion0.0.1-SNAPSHOT/versionpackagingwar/packagingdependenciesdependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion3.8.1/versionscopetest/scope/dependency!-- Spring dependencies --dependencygroupIdorg.springframework/groupIdartifactIdspring-core/artifactIdversion4.2.1.RELEASE/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-web/artifactIdversion4.2.1.RELEASE/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-webmvc/artifactIdversion4.2.1.RELEASE/version/dependency!-- Jackson JSON Processor --dependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactIdversion2.4.1/version/dependency!-- Spring Security Dependencies --dependencygroupIdorg.springframework.security/groupIdartifactIdspring-security-core/artifactIdversion3.2.3.RELEASE/version/dependencydependencygroupIdorg.springframework.security/groupIdartifactIdspring-security-web/artifactIdversion3.2.3.RELEASE/version/dependencydependencygroupIdorg.springframework.security/groupIdartifactIdspring-security-config/artifactIdversion3.2.3.RELEASE/version/dependencydependencygroupIdorg.springframework.security.oauth/groupIdartifactIdspring-security-oauth2/artifactIdversion1.0.0.RELEASE/version/dependency/dependencies
/project web.xml 更新web.xml文件以加载上下文文件并配置Spring Security过滤器该过滤器将在处理请求之前重定向身份验证和授权请求。 ?xml version1.0 encodingISO-8859-1?
web-app xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlnshttp://java.sun.com/xml/ns/javaeexsi:schemaLocationhttp://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsdidWebApp_ID version2.5display-nameSecureRESTWithOAuth/display-nameservletservlet-namemvc-dispatcher/servlet-nameservlet-classorg.springframework.web.servlet.DispatcherServlet/servlet-classload-on-startup1/load-on-startup/servletservlet-mappingservlet-namemvc-dispatcher/servlet-nameurl-pattern/*/url-pattern/servlet-mappinglistenerlistener-classorg.springframework.web.context.ContextLoaderListener/listener-class/listener!-- Loads context files --context-paramparam-namecontextConfigLocation/param-nameparam-value/WEB-INF/mvc-dispatcher-servlet.xml,/WEB-INF/spring-security.xml/param-value/context-param!-- Spring Security --filterfilter-namespringSecurityFilterChain/filter-namefilter-classorg.springframework.web.filter.DelegatingFilterProxy/filter-class/filterfilter-mappingfilter-namespringSecurityFilterChain/filter-nameurl-pattern/*/url-pattern/filter-mapping/web-app mvc-dispatcher-servlet.xml ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:contexthttp://www.springframework.org/schema/contextxmlns:utilhttp://www.springframework.org/schema/util xmlns:mvchttp://www.springframework.org/schema/mvcxsi:schemaLocationhttp://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.xsdcontext:component-scan base-packagecom.jcombat.controller /mvc:annotation-driven //beans 由于我们将使用admin JSP文件因此我们已经为其配置了相应的视图解析器。 现在让我们在其上下文文件中配置Spring Security OAuth。 spring-security.xml ?xml version1.0 encodingUTF-8 ?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:oauthhttp://www.springframework.org/schema/security/oauth2xmlns:contexthttp://www.springframework.org/schema/contextxmlns:sechttp://www.springframework.org/schema/security xmlns:mvchttp://www.springframework.org/schema/mvcxsi:schemaLocationhttp://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-sessionstatelessauthentication-manager-refclientAuthenticationManagerxmlnshttp://www.springframework.org/schema/securityintercept-url pattern/oauth/token accessIS_AUTHENTICATED_FULLY /anonymous enabledfalse /http-basic entry-point-refclientAuthenticationEntryPoint /custom-filter refclientCredentialsTokenEndpointFilterafterBASIC_AUTH_FILTER /access-denied-handler refoauthAccessDeniedHandler //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-sessionneverentry-point-refoauthAuthenticationEntryPointaccess-decision-manager-refaccessDecisionManagerxmlnshttp://www.springframework.org/schema/securityanonymous enabledfalse /intercept-url pattern/api/** accessROLE_APP /!-- Protect oauth clients with resource ids --custom-filter refresourceServerFilter beforePRE_AUTH_FILTER /access-denied-handler refoauthAccessDeniedHandler //httpbean idoauthAuthenticationEntryPointclassorg.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPointproperty namerealmName valuedemo/client //beanbean idclientAuthenticationEntryPointclassorg.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPointproperty namerealmName valuedemo/client /property nametypeName valueBasic //beanbean idoauthAccessDeniedHandlerclassorg.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler /bean idclientCredentialsTokenEndpointFilterclassorg.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilterproperty nameauthenticationManager refclientAuthenticationManager //beanbean idaccessDecisionManager classorg.springframework.security.access.vote.UnanimousBasedxmlnshttp://www.springframework.org/schema/beansconstructor-arglistbean classorg.springframework.security.oauth2.provider.vote.ScopeVoter /bean classorg.springframework.security.access.vote.RoleVoter /bean classorg.springframework.security.access.vote.AuthenticatedVoter //list/constructor-arg/beanauthentication-manager idclientAuthenticationManagerxmlnshttp://www.springframework.org/schema/securityauthentication-provider user-service-refclientDetailsUserService //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 aliasauthenticationManagerxmlnshttp://www.springframework.org/schema/securityauthentication-provideruser-serviceuser nameadmin password123 authoritiesROLE_APP //user-service/authentication-provider/authentication-managerbean idclientDetailsUserServiceclassorg.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsServiceconstructor-arg refclientDetails //bean!-- This defines the token store. We have currently used in-memory token store but we can instead use a user defined one --bean idtokenStoreclassorg.springframework.security.oauth2.provider.token.InMemoryTokenStore /!-- If need to store tokens in DB bean idtokenStoreclassorg.springframework.security.oauth2.provider.token.store.JdbcTokenStoreconstructor-arg refjdbcTemplate //bean --!-- This is where we defined token based configurations, token validity and other things --bean idtokenServicesclassorg.springframework.security.oauth2.provider.token.DefaultTokenServicesproperty nametokenStore reftokenStore /property namesupportRefreshToken valuetrue /property nameaccessTokenValiditySeconds value120 /property nameclientDetailsService refclientDetails //beanbean iduserApprovalHandlerclassorg.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandlerproperty nametokenServices reftokenServices //bean!-- The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization --oauth:authorization-serverclient-details-service-refclientDetails token-services-reftokenServicesuser-approval-handler-refuserApprovalHandleroauth: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 idresourceServerFilterresource-idadminProfile token-services-reftokenServices /!-- 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 idclientDetailsoauth:client client-idfbAppauthorized-grant-typespassword,refresh_tokensecretfbApp authoritiesROLE_APP resource-idsadminProfile //oauth:client-details-servicesec:global-method-securitypre-post-annotationsenabled proxy-target-classtruesec:expression-handler refoauthExpressionHandler //sec:global-method-securityoauth:expression-handler idoauthExpressionHandler /oauth:web-expression-handler idoauthWebExpressionHandler //beans 我们已经配置了/ oauth / token URL来发布访问和刷新令牌并且/ api / **映射到服务器上实际受保护的资源。 因此要访问与模式/ api / **匹配的任何URL需要将有效令牌与请求一起传递。 身份验证管理器是进行身份验证的容器。 在我们的情况下身份验证管理器检查– 用户是否通过身份验证。 用户是否请求了正确的客户ID。 如果client-id正确则该用户是否有权使用它来访问服务器上的管理配置文件。 请参阅以下代码段– authentication-manager idclientAuthenticationManagerxmlnshttp://www.springframework.org/schema/securityauthentication-provider user-service-refclientDetailsUserService /
/authentication-managerbean idclientDetailsUserServiceclassorg.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsServiceconstructor-arg refclientDetails /
/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 idclientDetailsoauth:client client-idfbAppauthorized-grant-typespassword,refresh_tokensecretfbApp authoritiesROLE_APP resource-idsadminProfile /
/oauth:client-details-service 用户通过身份验证后 授权服务器将调用tokenServices并颁发访问令牌。 oauth:authorization-serverclient-details-service-refclientDetails token-services-reftokenServicesuser-approval-handler-refuserApprovalHandleroauth:authorization-code /oauth:implicit /oauth:refresh-token /oauth:client-credentials /oauth:password /
/oauth:authorization-serverbean idtokenServicesclassorg.springframework.security.oauth2.provider.token.DefaultTokenServicesproperty nametokenStore reftokenStore /property namesupportRefreshToken valuetrue /property nameaccessTokenValiditySeconds value120 /property nameclientDetailsService refclientDetails /
/beanbean idtokenStoreclassorg.springframework.security.oauth2.provider.token.InMemoryTokenStore /bean iduserApprovalHandlerclassorg.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandlerproperty nametokenServices reftokenServices /
/bean 在指定客户端时请注意我们指定的授权类型即password 。 oauth:client-details-service idclientDetailsoauth:client client-idfbAppauthorized-grant-typespassword,refresh_tokensecretfbApp authoritiesROLE_APP resource-idsadminProfile /
/oauth:client-details-servicegt 发出访问令牌后我们便可以访问服务器上受保护的资源并将其与每个请求一起传递。 最后让我们看看我们编写的Spring Controller – EmployeeController.java package com.jcombat.controller;import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import com.jcombat.bean.Employee;RestController
RequestMapping(value /api/Employee)
public class EmployeeController {RequestMapping(value /{name}, method RequestMethod.GET)public Employee process(PathVariable(name) String name,RequestParam(value empId, required false, defaultValue 00000) final String id) {Employee employee new Employee();employee.setEmpId(id);employee.setName(name);return employee;}
};4.运行应用程序 要运行该应用程序让我们首先从授权服务器请求访问令牌- http// localhost8080 / SecureRESTWithOAuth / oauth / token grant_type 密码和client_id fbApp client_secret fbApp 用户名 admin 密码 123 { value:a7718567-6e38-4be3-aa41-382c90e042e0,expiration:1505631027817,tokenType:bearer,refreshToken:{ value:7792b077-7ae0-427e-8170-8b1440e5fefd,expiration:1508222907814},scope:[ ],additionalInformation:{ },expiresIn:109,expired:false
} 生成访问令牌后我们准备将其与服务器上对受保护资源的所有后续请求一起传递。 http// localhost8080 / SecureRESTWithOAuth / api / Employee / abhimanyu access_token 7792b077-7ae0-427e-8170-8b1440e5fefd 5.下载代码 下载源代码 翻译自: https://www.javacodegeeks.com/2017/09/secure-rest-service-oauth2-tokens.html