Java Spring MVC + Spring Security - 使用 JSON 的控制器身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21144120/
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
Spring MVC + Spring Security - Controller Authentication using JSON
提问by Rodrigo Rodrigues
I'd like to use simple Spring controller to authenticate the Users using Spring Security.
我想使用简单的 Spring 控制器来验证使用 Spring Security 的用户。
My Controller
我的控制器
@Controller
@Scope("request")
public class Authenticator {
private String username;
private String password;
@Autowired
private AuthenticationManager authenticationManager;
@RequestMapping(value = "/login", method = {RequestMethod.POST })
public @ResponseBody String authentication(@RequestParam("login") String userName,
@RequestParam("password") String password, HttpServletRequest request) {
this.username = userName;
this.password = password;
Authentication authenticationToken = new UsernamePasswordAuthenticationToken(
userName, password);
try {
Authentication authentication = authenticationManager
.authenticate(authenticationToken);
SecurityContext securityContext = SecurityContextHolder
.getContext();
securityContext.setAuthentication(authentication);
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
return "sucess";
} catch (AuthenticationException ex) {
return "fail " + ex.getMessage();
}
}
My spring-security.xml
我的 spring-security.xml
<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.2.xsd">
<http pattern="/resources/**" security="none" />
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/logout" access="permitAll" />
<intercept-url pattern="/accessdenied" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<form-login />
<logout logout-success-url="/logout" />
<!-- <session-management invalid-session-url="/loginlimmit">
<concurrency-control error-if-maximum-exceeded="true"
max-sessions="1" />
</session-management> -->
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="a" password="a" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
This works fine
这工作正常
1 - if I try to access http: //localhost/app is redirect to http: //localhost/app/spring_security_login to login as expected
1 - 如果我尝试访问 http: //localhost/app 重定向到 http: //localhost/app/spring_security_login 以按预期登录
2 - if I send POST method to http: //localhost/app/login works, I receive the message sucess or fail as expected using credentials username=a and password=a as defined in Spring-security.xml in authentication provider, so it really authenticate using spring .security.
2 - 如果我将 POST 方法发送到 http: //localhost/app/login 工作,我会使用身份验证提供程序的 Spring-security.xml 中定义的凭据 username=a 和 password=a 按预期收到消息成功或失败,所以它确实使用 spring .security 进行身份验证。
The problems
问题
After send POST method and get login sucess, if I try to acess http: //localhost/app is redirect to http: //localhost/app/spring_security_login , so I cant undestand beacause the authentication worked fine!
发送 POST 方法并获得登录成功后,如果我尝试访问 http: //localhost/app 被重定向到 http: //localhost/app/spring_security_login ,所以我无法理解,因为身份验证工作正常!
How can get User authenticated in others controllers?
如何在其他控制器中对用户进行身份验证?
My goals is develop an application with Spring MVC but I will not use as standard web application, it will works like Backend application and the frontend will be other application, such as desktop, mobile, vaadin framework and these application will comunicate using JSON, the Spring MVC works fine to this, but I need to implement the authentication, in this case, using Spring Security.
我的目标是使用 Spring MVC 开发一个应用程序,但我不会将其用作标准的 Web 应用程序,它将像后端应用程序一样工作,前端将是其他应用程序,例如桌面、移动、vaadin 框架,这些应用程序将使用 JSON 进行通信, Spring MVC 对此工作正常,但我需要实现身份验证,在这种情况下,使用 Spring Security。
any hep?
任何hep?
回答by Mani
1 - if I try to access http: //localhost/app is redirect to http: //localhost/app/spring_security_login to login as expected
If the normal way of login works and its not redirecting to login page again when you request the http: //localhost/app
then your configuration is good.
如果正常的登录方式有效并且在您请求时不会再次重定向到登录页面,http: //localhost/app
那么您的配置是好的。
After send POST method and get login sucess, if I try to acess http: //localhost/app is redirect to http: //localhost/app/spring_security_login , so I cant undestand beacause the authentication worked fine!
For each request , the application considers as new session. if you have configured Spring Security filter already in web.xml ( which makes the point 1 works fine) should create Session for you, So you can just call getSession()
instead of getSession(true)
in your controller.
对于每个请求,应用程序将其视为新会话。如果你已经在 web.xml 中配置了 Spring Security 过滤器(这使得第 1 点工作正常)应该为你创建 Session,所以你可以调用getSession()
而不是getSession(true)
在你的控制器中。
Just log the session id between the request and see the sessions are different. it may be due to the way you are calling from client.
只需记录请求之间的会话 ID 即可查看会话是否不同。这可能是由于您从客户端调用的方式。
回答by SergeyB
You don't need to setup a controller, Spring Security has a chain of filters it uses to authenticate, you just need to post your username/password to that chain.
您不需要设置控制器,Spring Security 有一系列用于身份验证的过滤器,您只需要将您的用户名/密码发布到该链中。
<form-login
password-parameter="password" --> password field
username-parameter="username" --> username field
login-processing-url="/security/j_spring_security_check" --> set your form's action attribute to this URL, no need to implement anything at that URL
login-page="/login" --> login page
/>