简体   繁体   中英

Programmatically login on Spring Security and authenticate on AngularJS (JHipster)

I need to authenticate a JHipster (Spring Security/AngularJS) user after a regular GET request is made from the browser, and then redirect to the AngularJS app (for OpenID authentication)

@GetMapping("/login")
@Timed
public void login(HttpServletResponse response) throws Exception {
    User user = userRepository.findOneByLogin("user").get(); // For testing purposes
    Authentication auth = new UsernamePasswordAuthenticationToken(user, null);
    SecurityContextHolder.getContext().setAuthentication(auth);

    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", "http://localhost:8080/#/");
}

After the redirect to " http://localhost:8080/#/ " is made, the response header comes with a JSESSIONID, but I don't know if that's the token that I need (is this the "user" authenticated token?), and it doesn't persist in the browser cookies (maybe because of the redirect?)

If I login using the default JHipster AngularJS username/password form, the response headers comes with

Set-Cookie:XSRF-TOKEN=108cadcf-2005-4e36-b055-438d75dc1ce9; path=/
Set-Cookie:JSESSIONID=foVcxycPQbUgS6nviKG1ftXSIgnlgDJdtxEGCSGZ; path=/; HttpOnly
Set-Cookie:remember-me=N2pNMGFRRGJENldhZWpQTGV2d1k6c3NOTkk1WWpnR28xcWRldDE2T3U; path=/; HttpOnly; Max-Age=2678400; Expires=Sun, 07-May-2017 07:40:16 GMT

I think the solution here would be to programmatically login the user, get a valid JSESSIONID token, and set it in the browser as a cookie while/after using the Location Header to redirect, but I'm having trouble with these steps. Any help is appreciated.

Actually, this line wasn't really authenticating the way I wanted it to:

Authentication auth = new UsernamePasswordAuthenticationToken(user, null);

The JSESSIONID was being set, but after a failed authentication upon a request it was being destroyed.

I changed to this:

Authentication auth = new UsernamePasswordAuthenticationToken(user, null, new ArrayList<GrantedAuthority>());

By using a different constructor it is now authenticating properly.

JHipster provides OpenID authentication out of the box (called 'Social login') and it's much more complicated than 'regular GET request', so probably best solution will be to start with existing template instead of crafting your own.

Next, 'JSESSIONID' cookie and request parameter are not controlled/created/modified by JHipster or Spring Security, this is on container level, part of servlet specification and fully controlled by servlet container, used internally (one of cases) to instantiate/get session beans. You should not attempt to overwrite them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM