问题
I am securing my REST API using Basic-Auth.
I have learned that for a stateless API,
the backend should send a cookie
(with both the httpOnly
and the secure
flag) for basic authentication,
which then will be added to each request.
Here are my questions:
- What should be the name of that cookie?
- How to set the cookie?
- How will the Spring security layer identify and extract the Base64 encoded credentials from that cookie?
Currently, this is my security config:
@Override
protected void configure(HttpSecurity http) throws Exception {// @formatter:off
http
.cors()
.and().authorizeRequests()
.antMatchers("/signup/**").permitAll()
.anyRequest().authenticated()
.and().httpBasic()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable()
;
// @formatter:off
}
Since I have no idea how to set the authentication cookie, I tried this:
@Controller
@RequestMapping("/login")
public class AuthController {
@GetMapping
@ResponseStatus(value=HttpStatus.OK)
public void loginUser( final HttpServletResponse response) {
response.addCookie(new Cookie("something", "value"));
}
}
http://localhost:8080/login
is a URL which is basic auth protected,
if the user provides correct credentials,
then it sends the authentication cookie with the response.
Also, I have no idea where to acquire the username password for this current user.
UPDATE: I managed to add the cookie to the response using below:
@GetMapping
@ResponseStatus(value=HttpStatus.OK)
public void loginUser( final HttpServletRequest request ,final HttpServletResponse response) throws UnsupportedEncodingException {
setAuthCookieToResonse(request,response);
}
private void setAuthCookieToResonse(final HttpServletRequest request ,final HttpServletResponse response) throws UnsupportedEncodingException {
String cookieKey = "auth";
String cookieValue = request.getHeader("Authorization");
if (cookieValue != null) {
Cookie cookie = new Cookie(cookieKey, cookieValue);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
}
So, now the basic idea is: With each request, this cookie will be sent. This reduces the extra overhead of adding the Authorization
header by the front-end application.
Now, the only part left is: Since with each request a auth cookie will be attached, I need to somehow take that cookie from the request
and pass it to the BasicAuthenticationFilter
in a way that the spring-security can extract the username and password from this cookie.
My idea: create a Filter(like below) and extract the credentials from cookie
, then add the Authorization
header from that cookie to the request
like Basic xxxxxxx=
.
来源:https://stackoverflow.com/questions/54554510/how-to-add-authentication-cookie-to-the-rest-api-response-using-spring-security