spring security config for authenticated users - spring

Good day. I would like to know how to block access to the registration page for users who have already been authenticated
Right now my configuration looks like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/registration").permitAll()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/hello")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/hello")
.permitAll();
}

You can directly write the if condition in your controller to access the login page
as below code
#GetMapping("/login")
public String loginPage(Model model) {
User user = new User();
model.addAttribute("user", user);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
return "/login";
}
return "redirect:/";
}

Related

Two identical post-methods, first is executed, second one is not allowed 405

I just wonder what can go wrong
#PostMapping("/login")
public ResponseEntity<TokenDTO> login(#RequestBody LoginDTO loginDTO) {
return ResponseEntity.ok(loginService.login(loginDTO));
}
#PostMapping("/logout")
public ResponseEntity<?> logout(#RequestBody LoginDTO loginDTO) {
Guest guest = guestDao.getGuestByLogin(loginDTO.getLogin());
guest.getTokens().clear();
return ResponseEntity.ok("Logout successfully");
}
SecurityConfig:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(tokenAuthFilter, BasicAuthenticationFilter.class)
.authenticationProvider(tokenAuthProvider)
.authorizeRequests()
.antMatchers("/guests/**", "/rooms/**", "/maintenances/**")
.authenticated()
.and()
.authorizeRequests()
.antMatchers("/login/**", "/logout/**").permitAll();
enter image description here - /login executed
enter image description here - /logout 405 not allowed

Spring Boot HttpSecurity redirect to defaultSuccessUrl even if the role differs

I'm trying to make a simple login page with spring boot 2.3.1
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(
"/",
"/home",
"/test",
"/resources/**"
)
.permitAll()
.antMatchers("/demo").hasAnyRole( "USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/demo")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.invalidateHttpSession(true)
.and()
.exceptionHandling().accessDeniedPage("/403")
.and().httpBasic();
}
Here is the code from my MyUserDetailsService
#Service
public class MyUserDetailsService implements UserDetailsService {
#Autowired
private UserService userService;
#Override
#Transactional
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
User user = userService.findUserByUserName(userName);
if (null ==user) {
throw (new UsernameNotFoundException("no user found!"));
}
List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
Set<GrantedAuthority> roles = new HashSet<GrantedAuthority>();
for (Role role : userRoles) {
roles.add(new SimpleGrantedAuthority(role.getRole()));
}
List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles);
return grantedAuthorities;
}
private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(),
user.getActive(), true, true, true, authorities);
}
}
I have an user in database (demo with role ADMIN). I don't understand why after I click on the submit button it's make redirect to /demo route. For me the role USER, means to force the login sistem to make the redirect to "/demo" route only if the form submited match the user, password and the role.
How can i change the "configure" method to allow redirect to demo route only when the credential from login form match the user from database (user, password and role)?
p.s please excuse my bad english
Change
.antMatchers("/demo").hasAnyRole( "USER") // <-- is ignored due to later duplication
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/demo")
.permitAll() // <--- permit all for /demo
To:
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/demo")
.hasAnyRole( "USER") // <-- USER for /demo

How do I make logout possible using Google OAuth2?

I am trying to do log-out, and I am using Spring Boot 2.1.7.RELEASE, and Google OAuth2.
This is my class implementing WebSecurityConfigurerAdapter.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers().frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/", "/css/**", "/images/**", "/js/**", "/h2-console/**").permitAll()
.antMatchers("/**").hasRole(Role.USER.name())
.anyRequest().authenticated()
.and()
.logout().logoutUrl("/logout").invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessUrl("/").deleteCookies("JSESSIONID").permitAll()
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.oauth2Login()
.userInfoEndpoint()
.userService(customOAuth2UserService);
}
And this is my #Controller code for Http-GET request, "/logout".
#GetMapping("/logout")
public String logout(HttpServletRequest request, HttpServletResponse response) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
new SecurityContextLogoutHandler().logout(request, response, authentication);
}
SecurityContextHolder.getContext().setAuthentication(null);
return "index";
}
I tried almost everything I googled and saw on Stackoverflow, but I seem to fail to completely logout every time.

Manage User Redirect Spring Security

i'm new to spring security can any one guide me how to do this. my configuration class of spring security is mention below: i made my home page "/" visible to all user. so i didn't use "/" in http.antmatchs("/") in home page my nav bar has link for "login and signup". after successful login user redirect to "buyer/list" endpoint which i mention in configuration. what i want is "login user" can't visit homepage again. for this i also use
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
for "/" mapping controller, but it throw nullPointerException. can any one guide me how do i proceed. if there is other approach please mention.
Configuration
#EnableWebSecurity
public class SecureConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsService userDetailsService;
#Value("${winni.auth.exit}")
private String authExit;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/web/**", "/action/**", "/cart/**", "/cart/xhr/**", "/buyer/**","/profile/**","/chat/**","/order/**")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/buyer/list", true).permitAll().and()
.logout().logoutSuccessUrl(authExit);
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/assets/**");
}
}
So you want that only unauthenticated users can access "/" and "/login" and only authenticated users on the other pages. I would do something like this:
http
.authorizeRequests()
.antMatchers("/web/**", "/action/**", "/cart/**", "/cart/xhr/**", "/buyer/**","/profile/**","/chat/**","/order/**")
.authenticated()
.and()
.antMatchers("/", "/login")
.anonymous()
.and()
.formLogin().loginPage("/login")
.defaultSuccessUrl("/buyer/list", true)
.and()
.logout()
.logoutSuccessUrl("/");

Authentication failure redirect with request params not working

I am trying to configure my own success and authentication failure handlers. On authentication failure I want to redirect back to my login page with a request parameter, the presence of this parameter will output the error message on my login page. However although on error I am getting redirected back to my login page, the request parameter is always null.
Code below:
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html").permitAll()
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/login")
.successHandler(successHandler())
.failureHandler(handleAuthenticationFailure());
}
#Autowired
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//database checks
}
};
}
/**
* Authentication success handler defines action when successfully authenticated
* #return
*/
#Bean
public AuthenticationSuccessHandler successHandler(){
return new AuthenticationSuccessHandler() {
#Override
public void onAuthenticationSuccess(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Authentication authentication)
throws IOException, ServletException {
// custom auth success here
httpResponse.setStatus(HttpServletResponse.SC_OK);
SavedRequest savedRequest = (SavedRequest) httpRequest.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
httpResponse.sendRedirect(savedRequest.getRedirectUrl());
}
};
}
#Bean
public AuthenticationFailureHandler handleAuthenticationFailure() {
return new SimpleUrlAuthenticationFailureHandler() {
#Override
public void onAuthenticationFailure(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
AuthenticationException authenticationException) throws IOException, ServletException {
// custom failure code here
setDefaultFailureUrl("/login.html?error=fail");
super.onAuthenticationFailure(httpRequest, httpResponse, authenticationException);
}
};
}
Try with this:
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// .......
response.sendRedirect("/login.html?error=fail");
}
Update:
It's really important that the "/login.html?error=fail" is added to an authorizeRequests() section otherwise the controller won't pick up the error parameter.
Replace .antMatchers("/login").permitAll() with .antMatchers("/login**").permitAll()
Also had problem with params (in my case when login was failed and some request params was added to url it redirected to login page without params).
This solved my problem
.antMatchers("/login**").permitAll()
I'm new in springBoot, if you are using spring boot 2.1.4.RELEASE, try this configuration:
http.csrf().disable()
.authorizeRequests()
// URLs matching for access rights
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
// form login
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.successHandler(sucessHandler)
.usernameParameter("email")
.passwordParameter("password")
.and()
// logout
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
To use the above-defined Spring Security configuration, we need to attach it to the web application. In this case, we don’t need any web.xml:
public class SpringApplicationInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[] {SecSecurityConfig.class};
}}
this means you create the following class which will be instanciated autoatically
SecSecurityConfig.class : is the class where you do all http.csrf().disable().authorizeRequests()... configurations
source : https://www.baeldung.com/spring-security-login
hope it helps :)

Resources