blob: df1ae38cb8eab250de8ede54cd4be0aefd31ef6b (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
package com.juick.server.security;
import com.juick.User;
import com.juick.server.security.entities.JuickUser;
import com.juick.service.UserService;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by aalexeev on 4/5/17.
*/
public class HashParamAuthenticationFilter extends OncePerRequestFilter {
public static final String PARAM_NAME = "hash";
private final UserService userService;
public HashParamAuthenticationFilter(UserService userService) {
this.userService = userService;
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String hash = request.getHeader(PARAM_NAME);
if (hash == null)
hash = request.getParameter(PARAM_NAME);
if (hash != null && authenticationIsRequired()) {
User user = userService.getUserByHash(hash);
if (!user.isAnonymous())
SecurityContextHolder.getContext().setAuthentication(
new RememberMeAuthenticationToken(hash, new JuickUser(user), JuickUser.USER_AUTHORITY));
}
filterChain.doFilter(request, response);
}
private boolean authenticationIsRequired() {
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
if (existingAuth == null || !existingAuth.isAuthenticated())
return true;
if (existingAuth instanceof AnonymousAuthenticationToken)
return true;
return false;
}
}
|