我正在做一些非常相似的事情。我正在为无状态 REST 后端进行身份验证,因此我希望用户进行一次身份验证,然后对于每个后续请求,身份验证必须是透明的。我为此使用令牌。登录时,用户提供的凭据用于身份验证和生成令牌(尽管最终我们希望使用外部服务来获取令牌)。令牌作为标头返回。然后 angularjs 前端在每个后续的 REST 调用中发送令牌。后端检查令牌的有效性,如果它是好的,则将'authenticated'标记为true。
这是我的 security-context.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<http use-expressions="true"
entry-point-ref="restAuthenticationEntryPoint"
create-session="stateless">
<intercept-url pattern="/secured/extreme/**" access="hasRole('ROLE_SUPERVISOR')"/>
<intercept-url pattern="/secured/**" access="isAuthenticated()" />
<intercept-url pattern="/j_spring_security_check" requires-channel="https" access="permitAll"/>
<intercept-url pattern="/logon.jsp" requires-channel="https" access="permitAll"/>
<sec:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
</http>
<beans:bean id="restAuthenticationEntryPoint" class="com.company.project.authentication.security.RestAuthenticationEntryPoint" />
<beans:bean id="authenticationTokenProcessingFilter" class="com.company.project.authentication.security.AuthenticationTokenProcessingFilter" >
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="userDetailsServices">
<beans:list>
<beans:ref bean="inMemoryUserDetailsService" />
<beans:ref bean="tmpUserDetailsService" />
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="tmpUserDetailsService" class="com.company.project.authentication.security.TokenUserDetailsServiceImpl" />
<user-service id="inMemoryUserDetailsService">
<user name="temporary" password="temporary" authorities="ROLE_SUPERVISOR" />
<user name="user" password="userPass" authorities="ROLE_USER" />
</user-service>
<authentication-manager alias="authenticationManager">
<!-- Use some hard-coded values for development -->
<authentication-provider user-service-ref="inMemoryUserDetailsService" />
<authentication-provider ref='companyLdapProvider' />
</authentication-manager>
对于身份验证过滤器,我将 UsernamePasswordAuthenticationFilter 子类化。当它是一个登录请求时,会通过身份验证提供者进行身份验证,然后生成一个令牌。如果从标头中读取令牌,则检查令牌以进行身份验证。这是我的身份验证过滤器(它还没有准备好生产,但它可以让您了解您可以做什么):
public class AuthenticationTokenProcessingFilter extends UsernamePasswordAuthenticationFilter {
//~ Static fields/initializers =====================================================================================
private static final String HEADER_AUTH_TOKEN = "X-Auth-Token";
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationTokenProcessingFilter.class);
private List<UserDetailsService> userDetailsServices = new ArrayList<UserDetailsService>();
//~ Constructors ===================================================================================================
public AuthenticationTokenProcessingFilter() {
super();
}
//~ Methods ========================================================================================================
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String authToken = this.extractAuthTokenFromRequest(request);
if (authToken == null) {
super.doFilter(request, res, chain);
return;
}
String userName = TokenUtils.getUserNameFromToken(authToken);
if (userName != null) {
UserDetails userDetails = loadUserByUsername(userName);
if (TokenUtils.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
UsernamePasswordAuthenticationToken authRequest = authenticateWithForm(request, response);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
Authentication authentication = this.getAuthenticationManager().authenticate(authRequest);
if (authentication.isAuthenticated()) {
try {
String authToken = TokenUtils.createToken(obtainUsername(request), obtainPassword(request));
LOGGER.info("Setting HTTP header {} = {}", HEADER_AUTH_TOKEN, authToken);
response.addHeader(HEADER_AUTH_TOKEN, authToken);
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
LOGGER.info("authorities = {}", authorities);
// Now we should make an in-memory table of the token and userdetails for later use
} catch(Exception e) {
LOGGER.warn("Error creating token for authentication. Authorization token head cannot be created.", e);
}
}
return authentication;
}
protected UsernamePasswordAuthenticationToken authenticateWithForm(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
return authRequest;
}
private String extractAuthTokenFromRequest(HttpServletRequest httpRequest) {
/* Get token from header */
String authToken = httpRequest.getHeader(HEADER_AUTH_TOKEN);
/* If token not found get it from request parameter */
if (authToken == null) {
authToken = httpRequest.getParameter("token");
}
return authToken;
}
public List<UserDetailsService> getUserDetailsServices() {
return userDetailsServices;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsServices.add(userDetailsService);
}
public void setUserDetailsServices(List<UserDetailsService> users) {
if (users != null) {
this.userDetailsServices.clear();
this.userDetailsServices.addAll(users);
}
}
private UserDetails loadUserByUsername(String username) {
UserDetails user = null;
List<Exception> exceptions = new ArrayList<Exception>();
for (UserDetailsService service: userDetailsServices) {
try {
user = service.loadUserByUsername(username);
break;
} catch (Exception e) {
LOGGER.warn("Could not load user by username {} with service {}", username, service.getClass().getName());
LOGGER.info("Exception is: ",e);
exceptions.add(e);
}
}
if (user == null && !exceptions.isEmpty()) {
throw new AuthenticationException(exceptions.get(0));
}
return user;
}
}
不过,我仍在努力完善 UserDetailsService。通常,您可以使用身份验证提供程序来获取 UserDetails,但由于我有一个无状态应用程序,所以当我想对令牌进行身份验证时,我必须确定要使用哪个 UserDetailsService。我目前正在使用自定义代码执行此操作。