我是Spring框架的新手,所以对于我的理解中的任何漏洞,我深表歉意。
我正在使用Auth0来保护我的API,这非常有效。我的设置和配置与Auth0文档中的suggested setup相同:
// SecurityConfig.java
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// auth0 config vars here
@Override
protected void configure(HttpSecurity http) {
JwtWebSecurityConfigurer
.forRS256(apiAudience, issuer)
.configure(http)
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/public").permitAll()
.antMatchers(HttpMethod.GET, "/api/private").authenticated();
}
}
通过此设置,将从jwt令牌sub
中将spring安全主体设置为userId(auth0|5b2b...
)。但是,我希望将其设置为匹配的用户(来自我的数据库),而不仅仅是userId。我的问题是如何做到这一点。
我尝试实现从this tutorial复制的自定义数据库支持的UserDetailsService。 但是,无论我如何尝试将其添加到conf中,都不会调用它。我尝试过以几种不同的方式添加它,但没有效果:
// SecurityConfig.java (changes only)
// My custom userDetailsService, overriding the loadUserByUsername
// method from Spring Framework's UserDetailsService.
@Autowired
private MyUserDetailsService userDetailsService;
protected void configure(HttpSecurity http) {
http.userDetailsService(userDetailsService); // Option 1
http.authenticationProvider(authenticationProvider()); // Option 2
JwtWebSecurityConfigurer
[...] // The rest unchanged from above
}
@Override // Option 3 & 4: Override the following method
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider()); // Option 3
auth.userDetailsService(userDetailsService); // Option 4
}
@Bean // Needed for Options 2 or 4
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
return authProvider;
}
不幸的是,由于我需要将其与Auth0身份验证结合使用,因此类似的“未调用userDetails”问题都没有帮助我。
我不能肯定我走在正确的道路上。对于这个极其常见的用例,我无法从Auth0找到任何文档,这对我来说似乎很奇怪,所以也许我缺少明显的东西。
PS:不确定是否相关,但始终在初始化期间记录以下内容。
Jun 27, 2018 11:25:22 AM com.test.UserRepository initDao
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
根据Ashish451的回答,我尝试复制他的CustomUserDetailsService,并将以下内容添加到我的SecurityConfig中:
@Autowired
private CustomUserDetailsService userService;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal( AuthenticationManagerBuilder auth ) throws Exception {
auth.userDetailsService( userService );
}
不幸的是,这些更改仍未调用CustomUserDetailsService。
添加@Norberto Ritzmann建议的日志记录方法时的输出:
Jul 04, 2018 3:49:22 PM com.test.repositories.UserRepositoryImpl initDao
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
Jul 04, 2018 3:49:22 PM com.test.runner.JettyRunner testUserDetailsImpl
INFO: UserDetailsService implementation: com.test.services.CustomUserDetailsService
答案 0 :(得分:2)
查看您的适配器代码,您将在configure自身中生成JWT令牌。 不确定发行人apiAudience是什么,但是我猜它生成了JWT的子。 您的问题是您想根据数据库更改JWT子项。
我最近在Spring Boot Application中实现了JWT安全性。
从数据库中获取用户名后,我正在设置用户名。
为清楚起见,我添加了带有pkg信息的代码。
//我的适配器类。除了您在 我添加了过滤器 的一件事之外,它与您的一样。在此过滤器中,我正在验证JWT令牌。每次触发安全休息URL时都会调用此过滤器。
import java.nio.charset.StandardCharsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import com.dev.myapp.jwt.model.CustomUserDetailsService;
import com.dev.myapp.security.RestAuthenticationEntryPoint;
import com.dev.myapp.security.TokenAuthenticationFilter;
import com.dev.myapp.security.TokenHelper;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
private CustomUserDetailsService jwtUserDetailsService; // Get UserDetail bu UserName
@Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint; // Handle any exception during Authentication
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
// Binds User service for User and Password Query from Database with Password Encryption
@Autowired
public void configureGlobal( AuthenticationManagerBuilder auth ) throws Exception {
auth.userDetailsService( jwtUserDetailsService )
.passwordEncoder( passwordEncoder() );
}
@Autowired
TokenHelper tokenHelper; // Contains method for JWT key Generation, Validation and many more...
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS ).and()
.exceptionHandling().authenticationEntryPoint( restAuthenticationEntryPoint ).and()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated().and()
.addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
http.csrf().disable();
}
// Patterns to ignore from JWT security check
@Override
public void configure(WebSecurity web) throws Exception {
// TokenAuthenticationFilter will ignore below paths
web.ignoring().antMatchers(
HttpMethod.POST,
"/auth/login"
);
web.ignoring().antMatchers(
HttpMethod.GET,
"/",
"/assets/**",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js"
);
}
}
//用户服务以获取用户详细信息
@Transactional
@Repository
public class CustomUserDetailsService implements UserDetailsService {
protected final Log LOGGER = LogFactory.getLog(getClass());
@Autowired
private UserRepo userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User uu = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
} else {
return user;
}
}
}
//未经授权的访问处理程序
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
// This is invoked when user tries to access a secured REST resource without supplying any credentials
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}
}
//用于验证JWT令牌的过滤器链
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;
public class TokenAuthenticationFilter extends OncePerRequestFilter {
protected final Log logger = LogFactory.getLog(getClass());
private TokenHelper tokenHelper;
private UserDetailsService userDetailsService;
public TokenAuthenticationFilter(TokenHelper tokenHelper, UserDetailsService userDetailsService) {
this.tokenHelper = tokenHelper;
this.userDetailsService = userDetailsService;
}
@Override
public void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain
) throws IOException, ServletException {
String username;
String authToken = tokenHelper.getToken(request);
logger.info("AuthToken: "+authToken);
if (authToken != null) {
// get username from token
username = tokenHelper.getUsernameFromToken(authToken);
logger.info("UserName: "+username);
if (username != null) {
// get user
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (tokenHelper.validateToken(authToken, userDetails)) {
// create authentication
TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
authentication.setToken(authToken);
SecurityContextHolder.getContext().setAuthentication(authentication); // Adding Token in Security COntext
}
}else{
logger.error("Something is wrong with Token.");
}
}
chain.doFilter(request, response);
}
}
// TokenBasedAuthentication类
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
public class TokenBasedAuthentication extends AbstractAuthenticationToken {
private static final long serialVersionUID = -8448265604081678951L;
private String token;
private final UserDetails principle;
public TokenBasedAuthentication( UserDetails principle ) {
super( principle.getAuthorities() );
this.principle = principle;
}
public String getToken() {
return token;
}
public void setToken( String token ) {
this.token = token;
}
@Override
public boolean isAuthenticated() {
return true;
}
@Override
public Object getCredentials() {
return token;
}
@Override
public UserDetails getPrincipal() {
return principle;
}
}
// JWT生成和验证逻辑的辅助类
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import com.dev.myapp.common.TimeProvider;
import com.dev.myapp.entity.User;
@Component
public class TokenHelper {
protected final Log LOGGER = LogFactory.getLog(getClass());
@Value("${app.name}") // reading details from property file added in Class path
private String APP_NAME;
@Value("${jwt.secret}")
public String SECRET;
@Value("${jwt.licenseSecret}")
public String LICENSE_SECRET;
@Value("${jwt.expires_in}")
private int EXPIRES_IN;
@Value("${jwt.mobile_expires_in}")
private int MOBILE_EXPIRES_IN;
@Value("${jwt.header}")
private String AUTH_HEADER;
@Autowired
TimeProvider timeProvider; // return current time. Basically Deployment time.
private SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS512;
// Generate Token based on UserName. You can Customize this
public String generateToken(String username) {
String audience = generateAudience();
return Jwts.builder()
.setIssuer( APP_NAME )
.setSubject(username)
.setAudience(audience)
.setIssuedAt(timeProvider.now())
.setExpiration(generateExpirationDate())
.signWith( SIGNATURE_ALGORITHM, SECRET )
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
User user = (User) userDetails;
final String username = getUsernameFromToken(token);
final Date created = getIssuedAtDateFromToken(token);
return (
username != null &&
username.equals(userDetails.getUsername())
);
}
// If Token is valid will extract all claim else throw appropriate error
private Claims getAllClaimsFromToken(String token) {
Claims claims;
try {
claims = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
LOGGER.error("Could not get all claims Token from passed token");
claims = null;
}
return claims;
}
private Date generateExpirationDate() {
long expiresIn = EXPIRES_IN;
return new Date(timeProvider.now().getTime() + expiresIn * 1000);
}
}
对于此日志
No authentication manager set. Reauthentication of users when changing passwords
由于您尚未实现名称为 loadUserByUsername 的方法。您正在获取此日志。
编辑1:
我仅使用过滤器链来验证令牌并将用户添加到安全上下文中,该上下文将从令牌中提取。...
我正在使用JWT,而您正在使用AuthO,只有实现不同。添加了完整的实现以实现完整的工作流程。
您专注于从 WebSecurityConfig 类实现 authenticationManagerBean 和 configureGlobal 以使用UserService。
和 TokenBasedAuthentication 类实现。
您可以跳过的其他内容。
答案 1 :(得分:2)
这可能是一个spring-boot上下文初始化问题,这意味着@Autowired
批注在Configuration类的初始化期间无法解决。
您可以在Configuration类的顶部尝试使用@ComponentScan()
批注,并显式加载MyUserDetailsService
。 (请参阅:https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-configuration-classes.html#using-boot-importing-configuration)。完成此操作后,我将在您的Configuration类中推荐以下内容:
@Autowired
private MyUserDetailsService userService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
希望这可以帮助您。
答案 2 :(得分:2)
我最终询问了Auth0支持,他们说目前无法在不修改库源代码的情况下修改主体。
但是,他们提供了另一种方法,即使用JWT验证库(例如https://github.com/auth0/java-jwt)代替其Spring Security API SDK。
我的解决方案是修改我的代码,使其仅将令牌用作主体。
答案 3 :(得分:1)
您可以使用覆盖的JwtAuthenticationProvider
方法扩展authenticate
,这会将您的用户置于Authentication
对象中:
com.auth0:auth0:1.14.2
,com.auth0:auth0-spring-security-api:1.2.5
,com.auth0:jwks-rsa:0.8.3
注意:以下代码段中可能存在一些错误,因为我已经将kotlin代码手动转换为Java
像往常一样配置SecurityConfig
,但通过修改后的身份验证提供程序:
@Autowired UserService userService;
...
@Override
protected void configure(HttpSecurity http) {
// same thing used in usual method `JwtWebSecurityConfigurer.forRS256(String audience, String issuer)`
JwkProvider jwkProvider = JwkProviderBuilder(issuer).build()
// provider deduced from existing default one
Auth0UserAuthenticationProvider authenticationProvider = new Auth0UserAuthenticationProvider(userService, jwkProvider, issuer, audience)
JwtWebSecurityConfigurer
.forRS256(apiAudience, issuer, authenticationProvider)
.configure(http)
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/public").permitAll()
.antMatchers(HttpMethod.GET, "/api/private").authenticated();
}
扩展默认值JwtAuthenticationProvider
,通常在方法JwtWebSecurityConfigurer.forRS256(String audience, String issuer)
中使用
public class Auth0UserAuthenticationProvider extends JwtAuthenticationProvider {
private final UserService userService;
public (UserService userService, JwkProvider jwkProvider, String issuer, String audience) {
super(jwkProvider, issuer, audience);
this.userService = userService;
}
/**
* Intercept Authentication object before it is set in context
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Authentication jwtAuth = super.authenticate(authentication);
// Use your service and get user details here
User user = userService.getDetailsOrWhatever(jwtAuth.getPrincipal().toString());
// TODO implement following class which merges Auth0 provided details with your user
return new MyAuthentication(jwtAuth, user);
}
}
实施自己的MyAuthentication.class
,它将覆盖getDetails()
并返回实际用户,而不是Auth0库提供的已解码令牌。
此后,用户将在
中可用SecurityContextHolder.getContext().getAuthentication().getDetails();
答案 4 :(得分:0)
如果您只想使用spring库,这就是我最后要做的。您可以更改Auth0UserDetailsService以从任何来源查询用户详细信息。
public class Auth0JwtAuthenticationProvider implements AuthenticationProvider {
@Autowired
ApplicationContext context;
@Autowired
@Qualifier("auth0UserDetailsService")
UserDetailsService auth0UserDetailsService;
private JwtAuthenticationProvider jwtAuthenticationProvider;
public Auth0JwtAuthenticationProvider() {
}
@PostConstruct
public void postConstruct() {
jwtAuthenticationProvider = new JwtAuthenticationProvider(context.getBean(JwtDecoder.class));
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Authentication token = jwtAuthenticationProvider.authenticate(authentication);
((AbstractAuthenticationToken) token).setDetails(auth0UserDetailsService.loadUserByUsername(authentication.getName()));
return token;
}
@Override
public boolean supports(Class<?> authentication) {
return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication);
}
}
对于UserDetailsService,我正在使用服务获取用户详细信息。
public class Auth0UserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
RestTemplate restTemplate = new RestTemplate();
.....
ResponseEntity<Auth0UserDetails> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Auth0UserDetails.class);
return responseEntity.getBody();
}
.....
}
UserDetails将包含您需要的所有详细信息。
public class Auth0UserDetails implements UserDetails {
@JsonProperty("name")
private String userName;
@JsonProperty("created_at")
private LocalDateTime createdAt;
@JsonProperty("email")
private String email;
@JsonProperty("email_verified")
private boolean isEmailVerified;
@JsonProperty("nickname")
private String nickName;
@JsonProperty("picture")
private String pictureURL;
@JsonProperty("updated_at")
private LocalDateTime updatedAt;
@JsonProperty("user_id")
private String userID;
... // Getters,Setter和覆盖方法。
}
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public Auth0JwtAuthenticationProvider auth0JwtAuthenticationProvider() {
return new Auth0JwtAuthenticationProvider();
}
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authenticationProvider(auth0JwtAuthenticationProvider()).authorizeRequests().
....
.oauth2ResourceServer().jwt();
}}