问题描述
我正在尝试使用 JWT 登录。我为此配置了两个不同的 websecurty。并且有两个表用于登录。但是authenticationManager.auth() 只能在一个地方登录
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
这个 bean 是存在的。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SuperSecurityConfig {
@Configuration
@Order(1)
public static class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private CustomJwtAuthenticationFilter customJwtAuthenticationFilter;
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Bean
@Primary
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().antMatcher("/admin/**")
.authorizeRequests()
.antMatchers("/admin/authenticate","/admin/register").permitAll()
.antMatchers("/admin/**").authenticated()
.and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).
and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().addFilterBefore(customJwtAuthenticationFilter,UsernamePasswordAuthenticationFilter.class);
}
}
@Configuration
@Order(2)
public static class OtpWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private OtpJwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private OtpJwtUserDetailsService jwtUserDetailsService;
@Autowired
private OtpJwtRequestFilter jwtRequestFilter;
@Bean
public PasswordEncoder otpPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// configure AuthenticationManager so that it kNows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
auth.userDetailsService(jwtUserDetailsService).passwordEncoder(otpPasswordEncoder());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().antMatcher("/user/**")
.authorizeRequests()
.antMatchers("/user/authenticateEndUser","/user/registerEndUser","/user/verifyMobile").permitAll()
.antMatchers("/user/**").authenticated()
.and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).
and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().addFilterBefore(jwtRequestFilter,UsernamePasswordAuthenticationFilter.class);
}
}
}
上面是我配置多入口点的地方 安全配置
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private SystemUserRepository systemUserRepo;
// @Autowired
// private PasswordEncoder bcryptEncoder;
@Autowired
private SpringSecurityConfiguration cusSecConfig;
@Autowired
private SystemUserRoleRepository systemUserRoleRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<GrantedAuthority> authorities;
Systemusermodel systemUser = systemUserRepo.findByEmailIgnoreCaseContaining(username);
if (systemUser != null) {
authorities = systemUser.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getAdminRoleName().name()))
.collect(Collectors.toList());
return new User(systemUser.getEmail(),systemUser.getpassword(),authorities);
}
throw new UsernameNotFoundException("User not found with the name " + username); }
public ResponsePayload save(SystemUserDto user) {
ResponsePayload responsePayload = new ResponsePayload();
Systemusermodel newUser = new Systemusermodel();
newUser.setFirstName(user.getFirstName());
newUser.setMiddleName(user.getMiddleName());
newUser.setLastName(user.getLastName());
newUser.setEmail(user.getEmail());
newUser.setMobileNumber(user.getMobileNumber());
newUser.setPassword(cusSecConfig.passwordEncoder().encode(user.getpassword()));
// List<String> strRoles = signUpRequest.getRole();
String strRoles = user.getSystemUserRole();
List<SystemUserRoleModel> roles = new ArrayList<>();
// Role roles;
if (strRoles == null) {
SystemUserRoleModel userRole = systemUserRoleRepository.findByAdminRoleName(ESystemUserRole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
} else {
switch (strRoles) {
case "admin":
SystemUserRoleModel adminRole = systemUserRoleRepository.findByAdminRoleName(ESystemUserRole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);
// roles = adminRole;
break;
case "user":
SystemUserRoleModel userRole = systemUserRoleRepository.findByAdminRoleName(ESystemUserRole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
// roles = stylishRole;
break;
default:
SystemUserRoleModel defaultUserRole = systemUserRoleRepository.findByAdminRoleName(ESystemUserRole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));;
roles.add(defaultUserRole);
}
}
newUser.setRoles(roles);
Systemusermodel returnedUser = systemUserRepo.save(newUser);
SystemUserDto afterSaveAdminDto = new SystemUserDto();
afterSaveAdminDto.setId(returnedUser.getId());
afterSaveAdminDto.setFirstName(returnedUser.getFirstName());
afterSaveAdminDto.setMiddleName(returnedUser.getMiddleName());
afterSaveAdminDto.setLastName(returnedUser.getLastName());
// List<String> roleDto = null;
// for(SystemUserRoleModel role : returnedUser.getRoles()) {
// String roleRet = role.getAdminRoleName().name();
// roleDto.add(roleRet);
//
// }
//afterSaveAdminDto.setSystemUserRole(roleDto);
responsePayload.setStatusCode(ResponseConstants.SUCCESS);
responsePayload.setStatus(ServerSuccess.SUCCESS);
responsePayload.setMessage(ServerSuccess.USER_CREATED);
responsePayload.setData(afterSaveAdminDto);
return responsePayload;
}
@Service
public class OtpJwtUserDetailsService implements UserDetailsService {
@Autowired
private EndUserRepository endUserRepository;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private OtpGenerator otpGen;
@Autowired
private OtpWebSecurityConfig otpSecconfig;
@Autowired
private OtpJwtTokenUtil jwtTokenUtil;
@Override
public UserDetails loadUserByUsername(String mobileNumber) throws UsernameNotFoundException {
Endusermodel user = endUserRepository.findByMobileNumber(mobileNumber);
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + mobileNumber);
}
return new org.springframework.security.core.userdetails.User(user.getMobileNumber(),user.getpassword(),new ArrayList<>());
}
public boolean verify(String mobileNumber) {
return endUserRepository.existsByMobileNumber(mobileNumber);
}
public ResponsePayload updateOtpEndUser(String mobileNumber){
ResponsePayload responsePayload = new ResponsePayload();
if(verify(mobileNumber)) {
String otpRet = otpGen.otpGen();
//String encryptedOtpRet = otpSecconfig.otpPasswordEncoder().encode(otpRet);
System.out.println("Otp for login: "+otpRet);
int returnInt = endUserRepository.setotpForEndusermodel(otpRet,mobileNumber);
if(returnInt>0) {
responsePayload.setStatusCode(ResponseConstants.SUCCESS);
responsePayload.setStatus(ServerSuccess.SUCCESS);
responsePayload.setMessage(ServerSuccess.USER_OTP_UPDATED);
responsePayload.setData(null);
return responsePayload;
}
else {
responsePayload.setStatusCode(ResponseConstants.BAD_REQUEST);
responsePayload.setStatus(ServerError.ERROR);
responsePayload.setMessage(ServerError.USER_OTP_UPDATE_ERROR);
responsePayload.setData(null);
return responsePayload;
}
}
else {
responsePayload.setStatusCode(ResponseConstants.BAD_REQUEST);
responsePayload.setStatus(ServerError.ERROR);
responsePayload.setMessage(ServerError.USER_OTP_UPDATE_ERROR);
responsePayload.setData(null);
return responsePayload;
}
}
public ResponsePayload save(EndUserDto user) {
ResponsePayload responsePayload = new ResponsePayload();
Endusermodel newUser = new Endusermodel();
newUser.setMobileNumber(user.getMobileNumber());
newUser.setFirstName(user.getFirstName());
newUser.setMiddleName(user.getMiddleName());
newUser.setLastName(user.getLastName());
Endusermodel savedUser = endUserRepository.save(newUser);
EndUserDto endUserDto = new EndUserDto();
endUserDto.setId(savedUser.getId());
endUserDto.setFirstName(savedUser.getFirstName());
endUserDto.setMiddleName(savedUser.getMiddleName());
endUserDto.setLastName(savedUser.getLastName());
responsePayload.setStatusCode(ResponseConstants.SUCCESS);
responsePayload.setStatus(ServerSuccess.SUCCESS);
responsePayload.setMessage(ServerSuccess.USER_CREATED);
responsePayload.setData(endUserDto);
return responsePayload;
}
public ResponsePayload logout(EndUserDto user) {
ResponsePayload responsePayload = new ResponsePayload();
Endusermodel updateUser = endUserRepository.findByMobileNumber(user.getMobileNumber());
updateUser.setPassword(null);
Endusermodel updatedUser = endUserRepository.save(updateUser);
responsePayload.setStatusCode(ResponseConstants.SUCCESS);
responsePayload.setStatus(ServerSuccess.SUCCESS);
responsePayload.setMessage(ServerSuccess.SUCCESS);
responsePayload.setData(null);
return responsePayload;
}
public ResponsePayload authenticateUser(AuthenticationRequest authenticationRequest) throws Exception
{
ResponsePayload responsePayload = new ResponsePayload();
try {
Authentication authentication =authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(),authenticationRequest.getpassword()));
if (authentication.isAuthenticated()) {
final UserDetails userDetails =
loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generatetoken(userDetails);
SecurityContextHolder.getContext().setAuthentication(authentication);
User user = (User) authentication.getPrincipal();
Endusermodel returnedMember = endUserRepository.findByMobileNumber(user.getUsername());
LoginResponseDto loginResponseDto = new LoginResponseDto();
loginResponseDto.setId(returnedMember.getId());
loginResponseDto.setFirstName(returnedMember.getFirstName());
loginResponseDto.setMiddleName(returnedMember.getMiddleName());
loginResponseDto.setLastName(returnedMember.getLastName());
loginResponseDto.setToken(token);
responsePayload.setStatusCode(ResponseConstants.SUCCESS);
responsePayload.setStatus(ServerSuccess.SUCCESS);
responsePayload.setMessage(ServerSuccess.LOGIN_SUCCESS);
responsePayload.setData(loginResponseDto);
return responsePayload;
}
} catch (disabledException e) {
throw new Exception("USER_disABLED",e);
} catch (BadCredentialsException e) {
responsePayload.setStatusCode(ResponseConstants.BAD_REQUEST);
responsePayload.setStatus(ServerError.ERROR);
responsePayload.setMessage(ServerError.USER_NOT_FOUND);
responsePayload.setData(null);
return responsePayload;
}
responsePayload.setStatusCode(ResponseConstants.BAD_REQUEST);
responsePayload.setStatus(ServerError.ERROR);
responsePayload.setMessage(ServerError.USER_NOT_FOUND);
responsePayload.setData(null);
return responsePayload;
}
private Authentication authenticate(String username,String password) throws Exception {
try {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(username,password));
if (authentication.isAuthenticated()) {
return authentication;
}
} catch (disabledException e) {
throw new Exception("USER_disABLED",e);
} catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS",e);
}
return null;
}
}
@CrossOrigin(origins={ "http://localhost:3000","http://localhost:4200","http://localhost:5000" })
@RestController
@RequestMapping("/admin")
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Autowired
private SystemUserRepository systemUserRepository;
@RequestMapping(value = "/authenticate",method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest)
throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),authenticationRequest.getpassword()));
} catch (disabledException e) {
throw new Exception("USER_disABLED",e);
}
catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS",e);
}
UserDetails userdetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
String token = jwtUtil.generatetoken(userdetails);
return ResponseEntity.ok(new AuthenticationResponse(token));
}
// @RequestMapping(value = "/authenticate",method = RequestMethod.POST)
// public ResponseEntity<ResponsePayload> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest)
// throws Exception {
// ResponsePayload responsePayload = new ResponsePayload();
// try {
// authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
// authenticationRequest.getUsername(),authenticationRequest.getpassword()));
// System.out.println("auth: "+authenticationRequest.getUsername()+""+ authenticationRequest.getpassword());
// UserDetails userdetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
// String token = jwtUtil.generatetoken(userdetails);
// Systemusermodel returnedUser= systemUserRepository.findByEmailIgnoreCaseContaining(userdetails.getUsername());
//
// LoginResponseDto loginResponseDto = new LoginResponseDto();
// loginResponseDto.setId(returnedUser.getId());
// loginResponseDto.setFirstName(returnedUser.getFirstName());
// loginResponseDto.setMiddleName(returnedUser.getMiddleName());
// loginResponseDto.setLastName(returnedUser.getLastName());
// loginResponseDto.setToken(token);
//// List<String> roleDto = null;
//// for(SystemUserRoleModel role : returnedUser.getRoles()) {
//// String roleRet = role.getAdminRoleName().name();
//// roleDto.add(roleRet);
//// loginResponseDto.setRoles(roleDto);
//// }
// responsePayload.setStatusCode(ResponseConstants.SUCCESS);
// responsePayload.setStatus(ServerSuccess.SUCCESS);
// responsePayload.setMessage(ServerSuccess.LOGIN_SUCCESS);
// responsePayload.setData(loginResponseDto);
// return ResponseEntity.status(responsePayload.getStatusCode()).body(responsePayload);
// } catch (disabledException e) {
// responsePayload.setStatusCode(ResponseConstants.BAD_REQUEST);
// responsePayload.setStatus(ServerError.ERROR);
// responsePayload.setMessage(ServerError.USER_disABLED);
// responsePayload.setData(new Exception("USER_disABLED",e));
// return ResponseEntity.status(responsePayload.getStatusCode()).body(responsePayload);
// }
// catch (BadCredentialsException e) {
// responsePayload.setStatusCode(ResponseConstants.BAD_REQUEST);
// responsePayload.setStatus(ServerError.ERROR);
// responsePayload.setMessage(ServerError.INVALID_CREDENTIALS);
// responsePayload.setData(new Exception("INVALID_CREDENTIALS",e));
// return ResponseEntity.status(responsePayload.getStatusCode()).body(responsePayload);
// }
// }
@RequestMapping(value = "/register",method = RequestMethod.POST)
public ResponseEntity<ResponsePayload> saveUser(@RequestBody SystemUserDto systemUserDto) throws Exception {
ResponsePayload responsePayload = userDetailsService.save(systemUserDto);
return ResponseEntity.status(responsePayload.getStatusCode()).body(responsePayload);
}
@RequestMapping(value = "/refreshtoken",method = RequestMethod.GET)
public ResponseEntity<ResponsePayload> refreshtoken(HttpServletRequest request) throws Exception {
// From the HttpRequest get the claims
ResponsePayload responsePayload = new ResponsePayload();
DefaultClaims claims = (io.jsonwebtoken.impl.DefaultClaims) request.getAttribute("claims");
Map<String,Object> expectedMap = getMapFromIoJsonwebtokenClaims(claims);
String token = jwtUtil.doGenerateRefreshToken(expectedMap,expectedMap.get("sub").toString());
Systemusermodel returnedUser= systemUserRepository.findByEmailIgnoreCaseContaining(request.getUserPrincipal().getName());
LoginResponseDto loginResponseDto = new LoginResponseDto();
loginResponseDto.setId(returnedUser.getId());
loginResponseDto.setFirstName(returnedUser.getFirstName());
loginResponseDto.setMiddleName(returnedUser.getMiddleName());
loginResponseDto.setLastName(returnedUser.getLastName());
loginResponseDto.setToken(token);
List<String> roleDto = null;
for(SystemUserRoleModel role : returnedUser.getRoles()) {
String roleRet = role.getAdminRoleName().name();
roleDto.add(roleRet);
loginResponseDto.setRoles(roleDto);
}
responsePayload.setStatusCode(ResponseConstants.SUCCESS);
responsePayload.setStatus(ServerSuccess.SUCCESS);
responsePayload.setMessage(ServerSuccess.LOGIN_SUCCESS);
responsePayload.setData(loginResponseDto);
return ResponseEntity.status(responsePayload.getStatusCode()).body(responsePayload);
}
@RequestMapping(value = "/me",method = RequestMethod.POST)
public void printUser() throws Exception {
System.out.println("i am admin");
}
public Map<String,Object> getMapFromIoJsonwebtokenClaims(DefaultClaims claims) {
Map<String,Object> expectedMap = new HashMap<String,Object>();
for (Entry<String,Object> entry : claims.entrySet()) {
expectedMap.put(entry.getKey(),entry.getValue());
}
return expectedMap;
}
}
@CrossOrigin(origins={ "http://localhost:3000","http://localhost:5000" })
@RestController
@RequestMapping("/user")
public class EndUserAuthenticationController {
@Autowired
private OtpJwtUserDetailsService userDetailsService;
@RequestMapping(value = "/verifyMobile",method = RequestMethod.POST)
public ResponseEntity<ResponsePayload> verifyMobile(@RequestParam String mobileNumber) throws Exception {
ResponsePayload res = userDetailsService.updateOtpEndUser(mobileNumber);
return ResponseEntity.status(res.getStatusCode()).body(res);
}
@RequestMapping(value = "/authenticateEndUser",method = RequestMethod.POST)
public ResponseEntity<ResponsePayload> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest) throws Exception {
ResponsePayload res = userDetailsService.authenticateUser(authenticationRequest);
return ResponseEntity.status(res.getStatusCode()).body(res);
}
@RequestMapping(value = "/registerEndUser",method = RequestMethod.POST)
public ResponseEntity<ResponsePayload> saveUser(@RequestBody EndUserDto user) throws Exception {
ResponsePayload res = userDetailsService.save(user);
return ResponseEntity.status(res.getStatusCode()).body(res);
}
@RequestMapping(value = "/me",method = RequestMethod.POST)
public void checkUser() throws Exception {
System.out.println("check user");
}
@RequestMapping(value = "/logoutEndUser",method = RequestMethod.POST)
public ResponseEntity<ResponsePayload> logoutUser(@RequestBody EndUserDto user) throws Exception {
ResponsePayload res = userDetailsService.logout(user);
return ResponseEntity.status(res.getStatusCode()).body(res);
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)