I have my securityconfig as :
package com.vaidiksanatansewa.guruji.security;
import javax.sql.DataSource;
import com.vaidiksanatansewa.guruji.service.UserloginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.vote.RoleVoter;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, IF(status=1, true, false) as enabled from users where username=? and status=1 ")
.authoritiesByUsernameQuery("select users.username as username, user_role.role as role from users inner join user_role on users.role_fid=user_role.id where users.username=? and users.status=1");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and()
.authorizeRequests().antMatchers( "/appointment/**").permitAll()
.antMatchers("/user/**").hasAnyAuthority("ADMIN","USER")
.and()
.csrf().disable();
}
}
and method annotated in controller as:
....
@RequestMapping("/user")
@Secured("ROLE_ADMIN")
public List<UserAll> getAll() {
return userService.getAll();
}
@RequestMapping("/user/{id}")
@Secured("ROLE_USER")
public UserAll getById(@PathVariable Long id) {
return userService.getById(id);
}
......
Without method authorization being enabled everthings working fine, but when it is enabled Im getting access denied error. It seems everything required is setup but still it isnt working. Can you help me in spotting it out??
It feels weird but replacing @Secured("ROLE_ADMIN")
with @PreAuthorize("hasAuthority('ADMIN')")
did the thing. I had tried doing @Secured("hasRole('ROLE_ADMIN')")
as well but that too didn't work.
Well, as for now it is solved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With