Пользователь уже вошел в систему как роль пользователя, и я хочу войти в систему как сотрудник, не отправляя форму входа, но аутентификация не удалась,
пожалуйста, проверьте код и помогите мне
@ RequestMapping (значение = "/ welcome", метод = RequestMethod.GET)
public ModelAndView logInSucess (@RequestParam (value = "_csrf", обязательный = false) String csrf,
Модель карты, запрос HttpServletRequest, ответ HttpServletResponse, основной принципал) генерирует исключение NormalUserNotFoundException {
LOG.info («Entry :: logInSucess в контроллере»);
Пользователь user = null;
ModelAndView modelAndView = new ModelAndView();
user = userDao.findById(principal.getName());
if (user.getRole().equals(SocialNetworkingUtil.ORG_ROLE)) {
modelAndView.setViewName("redirect:/company-home");
} else if (user.getRole().equals(SocialNetworkingUtil.USER_ROLE)
|| user.getRole().equals(SocialNetworkingUtil.EMPLOYEE_ROLE)) {
modelAndView.setViewName("redirect:/home");
} else if (user.getRole().equals(SocialNetworkingUtil.SUBADMIN_ROLE)) {
modelAndView.setViewName("redirect:/subadmin-home");
}
return modelAndView;
}
@ RequestMapping (value = "/ home")
public ModelAndView userHomePage (модель Model, запрос HttpServletRequest, ответ HttpServletResponse,
Принципал) выдает UserNotFoundException {
LOG.info («Entry :: userHomePage в контроллере»);
HttpSession session = request.getSession();
session.setMaxInactiveInterval(-1);/// for user session will never expire until user is not sending logout
/// request
ModelAndView modelAndView = new ModelAndView();
User user = userDao.findById(principal.getName());
LOG.info(user);
if (user.getRole().equals(SocialNetworkingUtil.USER_ROLE)) {
NormalUser normalUser = socialNetworkingService.findUserByUsername(user.getUsername());
session.setAttribute("username", normalUser.getEmail());
session.setAttribute("userId", normalUser.getUserId());
session.setAttribute("name", SocialNetworkingUtil.camelCase(normalUser.getName()));
session.setAttribute("user", user);
modelAndView.addObject("headerList", SocialNetworkingUtil.USER_SERVICES);
modelAndView.setViewName("user/home");
}
if (user.getRole().equals(SocialNetworkingUtil.EMPLOYEE_ROLE)) {
WorkingPlace work = workingPlaceDao.findByUserName(user.getUsername());
NormalUser normalUser = socialNetworkingService.findUserById(work.getId());
Company company = companyService.findById(work.getCompanyId());
session.setAttribute("username", normalUser.getEmail());
session.setAttribute("userId", normalUser.getUserId());
session.setAttribute("name", SocialNetworkingUtil.camelCase(normalUser.getName()));
session.setAttribute("workingpalce", work);
session.setAttribute("orgType",
SocialNetworkingUtil.SELECTED_ORGNIZATION_TYPE.PRIVATE.toString().toLowerCase());
session.setAttribute("orgId", company.getId());
modelAndView.setViewName("employee/home");
}
LOG.info("Exit :: userHomePage in controller");
return modelAndView;
}
Это контроллер Spring
@RequestMapping(value = "/switch-account", method = RequestMethod.GET)
public String switchAccount(
HttpServletRequest request,
HttpServletResponse response,
Principal principal) {
LOG.info("Entry::switchAccount");
HttpSession session = request.getSession();
String userId = (String) session.getAttribute("userId");
NormalUser normalUserObj = socialNetworkingService.findUserById(userId);
//make user is not present
User currentLoginuser = userDao.findById(normalUserObj.getLoginUser());
currentLoginuser.setPresent(false);
userDao.editUser(currentLoginuser);
User userObj = userDao.findById(normalUserObj.getWorkingEmailId());
Authentication authRequest = new UsernamePasswordAuthenticationToken(userObj.getUsername(), userObj.getPassword());
SecurityContextHolder.getContext().setAuthentication(authRequest);
LOG.info("Entry::switchAccount");
return "redirect:/welcome";
}
Это класс CustomUserDetailsService
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger LOG = Logger.getLogger(CustomUserDetailsService.class);
@Autowired
private UserDao userDao;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LOG.info("Entry :: loadUserByUsername-->" + username);
User user = getUserDetail(username);
List<GrantedAuthority> auth=getAuthorities(user.getRole());
org.springframework.security.core.userdetails.User userDetail;
userDetail = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
auth);
LOG.info(userDetail);
LOG.info("Exit :: loadUserByUsername ");
return userDetail;
}
public List<GrantedAuthority> getAuthorities(String role) {
LOG.info("Entry :: getAuthorities--->" + role);
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
if (role.equals(SocialNetworkingUtil.USER_ROLE)) {
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
} else if (role.equals(SocialNetworkingUtil.ORG_ROLE)) {
authList.add(new SimpleGrantedAuthority("ROLE_ORGANISATION"));
} else if (role.equals(SocialNetworkingUtil.SUBADMIN_ROLE)) {
authList.add(new SimpleGrantedAuthority("ROLE_SUBADMIN"));
}else if (role.equals(SocialNetworkingUtil.EMPLOYEE_ROLE)) {
authList.add(new SimpleGrantedAuthority("ROLE_EMPLOYEE"));
}
LOG.info("Exit :: getAuthorities");
return authList;
}
public User getUserDetail(String username) {
LOG.info("Entry :: getUserDetail--------------------------------------->" + username);
User user = userDao.findById(username);
LOG.info(user);
LOG.info("Exit :: getUserDetail");
return user;
}
}
файл конфигурации безопасности пружины
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/home*" access="hasAnyRole('ROLE_USER','ROLE_EMPLOYEE')" />
<intercept-url pattern="/company-home*" access="hasRole('ROLE_ORGANISATION')" />
<intercept-url pattern="/subadmin-home*" access="hasRole('ROLE_SUBADMIN')" />
<!--for web socket chat security -->
<intercept-url pattern="/ws/**" access="permitAll" />
<intercept-url pattern="/app/**" access="permitAll" />
<intercept-url pattern="/topic/**" access="permitAll" />
<intercept-url pattern="/topic/ws/*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/ws*" access="isAuthenticated()" />
<!-- hasRole('ROLE_ADMIN') -->
<intercept-url pattern="/chatprivate*" access="isAuthenticated()" />
<intercept-url pattern="/topic/wsresponse" access="isAuthenticated()" />
<form-login login-page="/login" default-target-url="/welcome"
authentication-failure-url="/"></form-login>
<logout logout-url="/logout" logout-success-url="/signout"
invalidate-session="false" />
<session-management session-fixation-protection="migrateSession"
invalid-session-url="/"
session-authentication-error-url="/login-error?authFailed=true">
<concurrency-control max-sessions="1"
expired-url="/Timeout?timeout=true" session-registry-alias="sessionRegistry" />
</session-management>
<csrf disabled="true"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder ref="encoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsService"
class="com.social.portal.service.CustomUserDetailsService" />
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<beans:bean id="sessionRegistry"
class="org.springframework.security.core.session.SessionRegistryImpl" />
</beans:beans>