authentication working not authorization. please i'm unable find what's going wrong.
controller
@restcontroller @requestmapping("/v1/user") public class usercontroller { @postauthorize("hasrole('role_admin')") //@preauthorize("hasrole('role_admin')"), both not working @requestmapping(method = requestmethod.delete) @responsestatus(httpstatus.no_content) public void deleteuser() { log.debug("only admin can access this"); authentication auth = securitycontextholder.getcontext().getauthentication(); system.out.println("user name "+auth.getname()); //prints - user name pratap system.out.println("user authorities "+auth.getauthorities()); // prints - user authorities [admin] } }
securityconfiguration.java
@configuration @enablewebsecurity @enableglobalmethodsecurity(prepostenabled = true) public class securityconfiguration extends websecurityconfigureradapter { @autowired private customuserdetailsservice customuserdetailsservice; @override protected void configure(httpsecurity http) throws exception { http.authorizerequests().anyrequest().fullyauthenticated().and(). httpbasic().and(). csrf().disable(); } @override protected void configure(authenticationmanagerbuilder auth) throws exception { auth.userdetailsservice(customuserdetailsservice); } }
customuserdetailsservice.java
@service public class customuserdetailsservice implements userdetailsservice { @autowired private userrepository userrepository; @override public userdetails loaduserbyusername(string username) throws usernamenotfoundexception { user user = userrepository.findbyusername(username); system.out.println("username "+user.getusername()); if(user != null) { return new org.springframework.security.core.userdetails.user(user.getusername(), user.getpassword(), true, true, true, true, authorityutils.createauthoritylist("admin")); } else { throw new usernamenotfoundexception("could not find user '" + username + "'"); } } }
error:
{ "timestamp": 1472789456591, "status": 403, "error": "forbidden", "message": "access denied", "path": "/v1/user/pratap" }
i got it. while adding roles should prefixed "role_"
authorityutils.createauthoritylist("role_admin", "role_user"));
and in @preauthorize, should without prefix "role_"
@preauthorize("hasrole('admin')")
Comments
Post a Comment