java Spring 中的自定义身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3205469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom authentication in Spring
提问by Buhake Sindi
I have a question. In Struts, I have an Action that deals with user authentication, i.e., I took the user's credentials and used a DAO to validate user credentials. I want to maintain the same setup in Spring. I'm using Spring 3.0.3 RELEASE.
我有个问题。在 Struts 中,我有一个处理用户身份验证的 Action,即,我获取了用户的凭据并使用 DAO 来验证用户凭据。我想在 Spring 中保持相同的设置。我正在使用 Spring 3.0.3 RELEASE。
My question is, I've read Spring Security and in there it specifies JDBC backend "Validation" provider. I want to know, how would, if the user clicked "login" that it submits the credentials to my controller to check for valid authentication?
我的问题是,我已经阅读了 Spring Security 并在其中指定了 JDBC 后端“验证”提供程序。我想知道,如果用户单击“登录”,它会如何将凭据提交给我的控制器以检查有效的身份验证?
The reason I want to do this that way is that I have a Service that handles user authentication and authorization.
我想这样做的原因是我有一个处理用户身份验证和授权的服务。
Thanks in advance.
提前致谢。
PSHow do I make some controller secure in Spring?
PPSI'm new to Spring
PS如何在 Spring 中使某些控制器安全?
PPS我是 Spring 的新手
回答by Barakat
You can create a custom authentication provider that implements org.springframework.security.authentication.AuthenticationProviderlike this
您可以创建一个实现org.springframework.security.authentication.AuthenticationProvider这样的自定义身份验证提供程序
package com.bzone.example;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
public class CustomAuthenticationProvider implements AuthenticationProvider{
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
// TODO call custom service or do whatever you want
return null;
}
@Override
public boolean supports(Class<? extends Object> authentication) {
// copied it from AbstractUserDetailsAuthenticationProvider
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
}
one more step is to configure spring security to use this custom authentication provider
另一个步骤是配置 spring security 以使用此自定义身份验证提供程序
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<!-- HTTP security configurations -->
<http auto-config="true" use-expressions="true">
<form-login login-processing-url="/static/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t"/>
<logout logout-url="/static/j_spring_security_logout"/>
<!-- Configure these elements to secure URIs in your application -->
<intercept-url pattern="/member/**" access="isAuthenticated()" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/static/**" access="permitAll" />
<intercept-url pattern="/**" access="permitAll" />
</http>
<!-- Configure Authentication mechanism -->
<authentication-manager alias="authenticationManager">
<authentication-provider ref="com.bzone.example.CustomAuthenticationProvider" />
</authentication-manager>
</beans:beans>
回答by axtavt
Usually Spring Security handles authentication inside its own code, using your code as strategies (authentication providers, user details services, etc). But you can handle authentication inside your own code.
通常 Spring Security 在它自己的代码中处理身份验证,使用你的代码作为策略(身份验证提供者、用户详细信息服务等)。但是您可以在自己的代码中处理身份验证。
In your action's code, when user credentials are correct, you will:
在您的操作代码中,当用户凭据正确时,您将:
- Create an
Authenticationcontaining user name and granted roles (you may useUsernamePasswordAuthenticationTokenas a convenient implementation). - Put it into security context:
SecurityContextHolder.getContext().setAuthentication(auth); - Broadcast the authentication success event using
AuthenticationEventPublisher.publishAuthenticationSuccess(...)(you may autowire it from the context or create aDefaultAuthenticationEventPublisherexplicitly). - Redirect user to the secured resource using
SavedRequestAwareAuthenticationSuccessHandler.onAuthenticationSuccess(...).
- 创建一个
Authentication包含用户名和授予的角色(您可以UsernamePasswordAuthenticationToken用作方便的实现)。 - 将其放入安全上下文中:
SecurityContextHolder.getContext().setAuthentication(auth); - 使用广播身份验证成功事件
AuthenticationEventPublisher.publishAuthenticationSuccess(...)(您可以从上下文自动装配它或DefaultAuthenticationEventPublisher显式创建)。 - 使用 将用户重定向到受保护的资源
SavedRequestAwareAuthenticationSuccessHandler.onAuthenticationSuccess(...)。
Also you need to supply an AuthenticationEntryPoint:
您还需要提供一个AuthenticationEntryPoint:
<bean id = "aep" class = "org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<!-- Your login page -->
<property name = "loginFormUrl" value = "/login" />
</bean>
<security:http entry-point-ref="aep">
...
</http>
However, if you are actually new in Spring, it may be better to avoid such a massive customizations and use the regular Spring Security architecture.
但是,如果您实际上是 Spring 新手,最好避免进行如此大规模的自定义并使用常规的 Spring Security 架构。
回答by Igor Artamonov
You can write you own validation mechanism for Spring Security. It have to consists of following parts:
您可以为 Spring Security 编写自己的验证机制。它必须由以下部分组成:
- Auth Filter - reads data from request, then call Auth Provider with credentials token (instance of class Authentication)
- Auth Provider - accepts this auth token (filter can create different tokents, and there can be different auth providers, for each token type), and try to authenticate (calling your service, at your case). After auth you may (or may not) call User Details Service or fill all user data right there
- User Details Service - load signed in user details from somewhere (from jdbc, other service, etc)
- 身份验证过滤器 - 从请求中读取数据,然后使用凭据令牌调用身份验证提供程序(类身份验证的实例)
- 身份验证提供程序 - 接受此身份验证令牌(过滤器可以创建不同的令牌,并且对于每种令牌类型可以有不同的身份验证提供程序),并尝试进行身份验证(根据您的情况调用您的服务)。身份验证后,您可以(或不可以)调用用户详细信息服务或在那里填写所有用户数据
- 用户详细信息服务 - 从某处(来自 jdbc、其他服务等)加载登录的用户详细信息

