我正在构建一个REST端点来验证(登录)用户。我正在使用自定义身份验证提供程序。
我的context.xml文件如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="com.foobar" />
<bean id="authDao" class="com.foobar.security.ldap.AuthProviderImpl">
</bean>
<bean id="myAuthProvider" class="com.foobar.security.MyAuthProvider">
</bean>
<security:authentication-manager id="authenticationManager" alias="authenticationManager">
<security:authentication-provider ref="myAuthProvider" />
</security:authentication-manager>
<security:http
realm="Protected API"
use-expressions="true"
auto-config="false"
create-session="stateless"
entry-point-ref="unauthorizedEntryPoint"
authentication-manager-ref="authenticationManager">
<security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
<security:intercept-url method="POST" pattern="/rest/autenticacion/login" access="permitAll" />
</security:http>
<bean id="unauthorizedEntryPoint" class="com.foobar.security.UnauthorizedEntryPoint" />
<bean id="authenticationTokenProcessingFilter" class="com.foobar.security.AuthenticationTokenProcessingFilter">
<constructor-arg ref="authDao" />
</bean>
</beans>
我的自定义身份验证提供程序(myAuthProvider)的定义如下
package com.foobar.security;
import java.util.ResourceBundle;
import javax.inject.Inject;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@Component
public class MyAuthProvider implements AuthenticationProvider {
private final ResourceBundle properties = ResourceBundle.getBundle("security");
@Inject
private UserDetailsService authDao;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String)authentication.getCredentials();
if (username.equals("admin") && password.equals("admin")) {
UserDetails userDetails = this.authDao.loadUserByUsername(username);
return new UsernamePasswordAuthenticationToken(username, password, userDetails.getAuthorities());
} else {
throw new BadCredentialsException("Bad username or password");
}
}
@Override
public boolean supports(Class<?> type) {
return true;
}
}
我的AuthProviderImpl类如下
package com.foobar.security.ldap;
import com.foobar.security.AuthProvider;
import java.util.Arrays;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
@Component
public class AuthProviderImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (username.equals("admin")) {
return new UserDetailsImpl("admin", Arrays.asList(new String[] { "ADMIN" }));
} else {
throw new UsernameNotFoundException("User not found");
}
}
}
我的UserDetailsImpl类如下
package com.foobar.security.ldap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class UserDetailsImpl implements UserDetails {
private final String username;
private final Date accountExpirationDate;
private final Boolean locked;
private final Date credentialsExpirationDate;
private final Boolean enabled;
private final List<String> roles;
public UserDetailsImpl(String username, Date accountExpirationDate, Boolean locked, Date credentialsExpirationDate, Boolean enabled, List<String> roles) {
this.username = username;
this.accountExpirationDate = accountExpirationDate;
this.locked = locked;
this.credentialsExpirationDate = credentialsExpirationDate;
this.enabled = enabled;
this.roles = roles;
}
public UserDetailsImpl(String username, List<String> roles) {
this.username = username;
this.accountExpirationDate = null;
this.locked = false;
this.credentialsExpirationDate = null;
this.enabled = true;
this.roles = roles;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> rolList = new ArrayList<GrantedAuthority>(this.roles.size());
for (String role : this.roles) {
rolList.add(new SimpleGrantedAuthority(role));
}
return rolList;
}
@Override
public String getPassword() {
return "";
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return this.accountExpirationDate != null && this.accountExpirationDate.after(new Date());
}
@Override
public boolean isAccountNonLocked() {
return !this.locked;
}
@Override
public boolean isCredentialsNonExpired() {
return this.credentialsExpirationDate != null && this.credentialsExpirationDate.after(new Date());
}
@Override
public boolean isEnabled() {
return this.enabled;
}
}
最后是我的REST端点
package com.foobar.rest;
import com.foobar.rest.dto.AutenticacionDTO;
import com.foobar.security.AuthProvider;
import com.foobar.security.TokenUtils;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
@Component
@Path("/autenticacion")
public class AutenticacionEndpoint {
private static final Logger logger = Logger.getLogger(AutenticacionEndpoint.class);
@Inject
private AuthProvider authDao;
@Autowired
@Qualifier("authenticationManager")
private AuthenticationManager authenticationManager;
@POST
@Path("login")
@Consumes("application/json")
public Response autenticar(AutenticacionDTO datos) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(datos.getUsuario(), datos.getClave());
AutenticacionDTO response;
UserDetails userDetails = null;
try {
userDetails = this.authDao.loadUserByUsername(datos.getUsuario());
/// THIS PART FAILS SINCE this.authenticationManager equals NULL - NullPointerException
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
Map<String, Boolean> roles = new HashMap<String, Boolean>(authentication.getAuthorities().size());
for (GrantedAuthority auth : authentication.getAuthorities()) {
roles.put(auth.getAuthority(), Boolean.TRUE);
}
response = new AutenticacionDTO(userDetails.getUsername(), Boolean.TRUE, null, null, TokenUtils.createToken(userDetails), !userDetails.isAccountNonExpired(), !userDetails.isCredentialsNonExpired());
return Response.status(Response.Status.OK).entity(response).build();
} catch (AuthenticationException ex) {
if (userDetails != null) {
response = new AutenticacionDTO(datos.getUsuario(), "Fallo en autenticacion", !userDetails.isAccountNonExpired(), !userDetails.isCredentialsNonExpired());
} else {
response = new AutenticacionDTO(datos.getUsuario(), false, "Usuario o contraseña inválidos");
}
return Response.status(Response.Status.UNAUTHORIZED).entity(response).build();
}
}
}
为什么不在端点注入authenticationManager
?在最后一节课中,我也将“authDao”作为@Autowired
但是在我用@Inject
注释替换它之前它没有被注入。但我不能将@Inject
与authenticationManager
一起使用,因为它不会将其识别为bean。
有什么想法吗?
答案 0 :(得分:1)
我不知道为什么,但是我的自定义课程没有注入Spring bean。我做了一个&#34;脏&#34;事情。在我的REST端点的autenticar
方法中,我添加了以下代码:
@Path("login")
@Consumes("application/json")
public Response autenticar(AutenticacionDTO datos, @Context ServletContext servletContext) {
logger.trace("AutenticacionEndpoint - autenticar");
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(datos.getUsuario(), datos.getClave());
AutenticacionDTO response;
UserDetails userDetails = null;
try {
userDetails = this.authDao.loadUserByUsername(datos.getUsuario());
if (this.authenticationManager == null) {
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
this.authenticationManager = ctx.getBean("authenticationManager", AuthenticationManager.class);
}
...
我希望这有助于某人,或者某人有更好的选择。