i am creating an application with Spring boot which requires first to login. The problem is that after login, my user becomes "anonymous" and i cannot create other requests, because they are forbidden if the user is not authenticated. For authentication i am using Spring security. Could you please tell me how save the user and to be always available after login.
Here is the Spring Configuration class:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomerAuthenticationProvider authenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/register")
.permitAll();
http
.authorizeRequests()
.anyRequest()
.authenticated();
http
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/homeLogged")
.permitAll();
http
.logout()
.logoutSuccessUrl("/login")
.permitAll();
}
}
Here is the JSP that will send Http Get request to the backend. Here i am logged in but the user is anonymous
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Business manager</title>
</head>
<script src="../../resources/js/jquery-3.4.1.js"></script>
<body>
<div class="container">
<div>
<h1>Business Manager</h1>
</div>
<div class="row">
<button id="goToNewSchedule">Create Schedule</button>
</div>
</div>
<script>
$("#goToNewSchedule").click(function(){
$.get("http://localhost:8080/homeLogged/schedule", function(){
console.log("Hello");
});
});
</script>
</body>
</html>
Its the controller that should receive the request
@Controller
@RequestMapping("/homeLogged/schedule")
@Log4j2
public class ScheduleController {
@Autowired
private ScheduleService scheduleService;
@GetMapping()
public String getSchedule() {
return "createSchedule";
}
It is the login controller
@Controller
@RequestMapping("/login")
@Log4j2
public class LoginController {
@Autowired
private CustomerAuthenticationProvider authenticationProvider;
@PostMapping
public ModelAndView login(@ModelAttribute("studio") Studio studio, HttpServletRequest request) {
log.info(studio.getUsername() + " user is logging");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(!(authentication.getAuthorities().contains(CustomerAuthenticationProvider.AUTHORITY_USER))){
Authentication auth = new UsernamePasswordAuthenticationToken(studio.getUsername(), studio.getPassword());
authenticationProvider.authenticate(auth);
}
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(30*60);
return new ModelAndView("redirect:homeLogged");
}
It seems to me that the LoginController is unnecessary.
The spring security configuration has already defined the authenticationProvider to authenticate your login, you don't need another Controller to do the same thing.
Try this:
http
.formLogin()
.defaultSuccessUrl("/homeLogged", true)
.permitAll();
And if you want to use your own custom login page, say login.jsp, you can add it after the formLogin() like this:
http
.formLogin().loginPage("/login.jsp")
.defaultSuccessUrl("/homeLogged", true)
.permitAll();
And in your login.jsp, you shall have three elements: 1. action: "login", which will post the request to url: login 2. username field 3. password field
and your authenticator defined in the your security config will authenticate the username and password and then redirect to the successful URL.
You're not really using Spring Security to its full extent. There might be a way to make it work using this strange way of logging in but what I would suggest is that you just do things the Spring way:
Make the entity you're using for logging in ( User.class
for example) implements Spring's UserDetails interface (don't forget to add logic to the boolean methods like isEnabled()
so that they don't always return false). Then choose a service to implement Spring's UserDetailsService interface which forces you to override the method loadUserByUsername()
which is used to get the user from the database. And lastly in your SecurityConfig
switch auth.authenticationProvider(authenticationProvider);
with auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
where userService
is the @Component
class which implements UserDetailsService and passwordEncoder
is just a BCryptPasswordEncoder @Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.