1

I'd like to use simple Spring controller to authenticate the Users using 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

<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

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.

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!

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.

any hep?

Lucky
  • 16,787
  • 19
  • 117
  • 151
Rodrigo Rodrigues
  • 649
  • 2
  • 12
  • 25
  • Why? Spring Security already does all that (and more) why are you working against/around instead of with the framework? – M. Deinum Jan 08 '16 at 14:10

2 Answers2

4

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.

<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 
/>
SergeyB
  • 9,478
  • 4
  • 33
  • 47
  • there is no form attribute in a desktop or moble application – KJEjava48 Feb 02 '16 at 11:41
  • 1
    @KJEjava48 you do a `POST` to `/security/j_spring_security_check` with `username` and `password` parameters. – SergeyB Feb 02 '16 at 19:29
  • the restTemplate allow me to use POST with only one parameter.So i need to pass this username and password using a Mulivaluemap or a json object.Then how spring security will split this username and password from the map or json??? – KJEjava48 Feb 03 '16 at 11:00
  • 1
    @KJEjava48, your question is how to use rest template, I suggest you google that. – SergeyB Feb 03 '16 at 16:37
  • no.I am asking you how this spring security will identify the username and password from json object from the post request – KJEjava48 Feb 04 '16 at 05:30
  • @KJEjava48 what are you talking about? What JSON object? There is no JSON object, there is username and password parameters, that's all. Learn the basics of HTTP. – SergeyB Feb 05 '16 at 14:18
0
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.

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.

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.

Mani
  • 3,274
  • 2
  • 17
  • 27