spring boot - What are the changes required to make oauth based authentication with mongodb? -
hi new mongodb , spring security.i trying create token key basen authorisation login below link followed create project set up:- spring security in memory allocation
the following code changes have made: -
1] resource server.
@configuration @enableresourceserver public class resourceserverconfiguration extends resourceserverconfigureradapter { private static final string resource_id = "my_rest_api"; @override public void configure(resourceserversecurityconfigurer resources) { resources.resourceid(resource_id).stateless(false); } @override public void configure(httpsecurity http) throws exception { http. anonymous().disable() .requestmatchers().antmatchers("/user/**") .and().authorizerequests() .antmatchers("/user/**").access("hasrole('admin')") .and().exceptionhandling().accessdeniedhandler(new oauth2accessdeniedhandler()); } }
2] authorization server: -
@configuration @enableauthorizationserver public class authorizationserverconfiguration extends authorizationserverconfigureradapter { private static string realm="my_oauth_realm"; @autowired private tokenstore tokenstore; @autowired private userapprovalhandler userapprovalhandler; @autowired @qualifier("authenticationmanagerbean") private authenticationmanager authenticationmanager; @override public void configure(clientdetailsserviceconfigurer clients) throws exception { clients.inmemory() .withclient("my-trusted-client") .authorizedgranttypes("password", "authorization_code", "refresh_token", "implicit") .authorities("role_client", "role_trusted_client") .scopes("read", "write", "trust") .secret("secret") .accesstokenvalidityseconds(120).//access token valid 2 minutes. refreshtokenvalidityseconds(600);//refresh token valid 10 minutes. } @override public void configure(authorizationserverendpointsconfigurer endpoints) throws exception { endpoints.tokenstore(tokenstore).userapprovalhandler(userapprovalhandler) .authenticationmanager(authenticationmanager); } @override public void configure(authorizationserversecurityconfigurer oauthserver) throws exception { oauthserver.realm(realm+"/client"); }
}
3] security configuration: -
@configuration @enablewebsecurity public class oauth2securityconfiguration extends websecurityconfigureradapter { @autowired private clientdetailsservice clientdetailsservice; @autowired public void globaluserdetails(authenticationmanagerbuilder auth) throws exception { auth.inmemoryauthentication() .withuser("bill").password("abc123").roles("admin").and() .withuser("bob").password("abc123").roles("user"); } @override protected void configure(httpsecurity http) throws exception { http .csrf().disable() .anonymous().disable() .authorizerequests() .antmatchers("/oauth/token").permitall(); } @override @bean public authenticationmanager authenticationmanagerbean() throws exception { return super.authenticationmanagerbean(); } @bean public tokenstore tokenstore() { return new inmemorytokenstore(); } @bean @autowired public tokenstoreuserapprovalhandler userapprovalhandler(tokenstore tokenstore){ tokenstoreuserapprovalhandler handler = new tokenstoreuserapprovalhandler(); handler.settokenstore(tokenstore); handler.setrequestfactory(new defaultoauth2requestfactory(clientdetailsservice)); handler.setclientdetailsservice(clientdetailsservice); return handler; } @bean @autowired public approvalstore approvalstore(tokenstore tokenstore) throws exception { tokenapprovalstore store = new tokenapprovalstore(); store.settokenstore(tokenstore); return store; } }
4] method security: -
@configuration @enableglobalmethodsecurity(prepostenabled = true, proxytargetclass = true) public class methodsecurityconfig extends globalmethodsecurityconfiguration { @autowired private oauth2securityconfiguration securityconfig; @override protected methodsecurityexpressionhandler createexpressionhandler() { return new oauth2methodsecurityexpressionhandler(); } }
5] rest controller: -
@restcontroller public class helloworldrestcontroller { @autowired userservice userservice; //service data retrieval/manipulation work //-------------------retrieve users-------------------------------------------------------- @requestmapping(value = "/user/", method = requestmethod.get) public responseentity<list<user>> listallusers() { list<user> users = userservice.findallusers(); if(users.isempty()){ return new responseentity<list<user>>(httpstatus.no_content);//you many decide return httpstatus.not_found } return new responseentity<list<user>>(users, httpstatus.ok); } //-------------------retrieve single user-------------------------------------------------------- @requestmapping(value = "/user/{id}", method = requestmethod.get, produces = {mediatype.application_json_value,mediatype.application_xml_value}) public responseentity<user> getuser(@pathvariable("id") long id) { system.out.println("fetching user id " + id); user user = userservice.findbyid(id); if (user == null) { system.out.println("user id " + id + " not found"); return new responseentity<user>(httpstatus.not_found); } return new responseentity<user>(user, httpstatus.ok); } //-------------------create user-------------------------------------------------------- @requestmapping(value = "/user/", method = requestmethod.post) public responseentity<void> createuser(@requestbody user user, uricomponentsbuilder ucbuilder) { system.out.println("creating user " + user.getname()); if (userservice.isuserexist(user)) { system.out.println("a user name " + user.getname() + " exist"); return new responseentity<void>(httpstatus.conflict); } userservice.saveuser(user); httpheaders headers = new httpheaders(); headers.setlocation(ucbuilder.path("/user/{id}").buildandexpand(user.getid()).touri()); return new responseentity<void>(headers, httpstatus.created); } //------------------- update user -------------------------------------------------------- @requestmapping(value = "/user/{id}", method = requestmethod.put) public responseentity<user> updateuser(@pathvariable("id") long id, @requestbody user user) { system.out.println("updating user " + id); user currentuser = userservice.findbyid(id); if (currentuser==null) { system.out.println("user id " + id + " not found"); return new responseentity<user>(httpstatus.not_found); } currentuser.setname(user.getname()); currentuser.setage(user.getage()); currentuser.setsalary(user.getsalary()); userservice.updateuser(currentuser); return new responseentity<user>(currentuser, httpstatus.ok); } //------------------- delete user -------------------------------------------------------- @requestmapping(value = "/user/{id}", method = requestmethod.delete) public responseentity<user> deleteuser(@pathvariable("id") long id) { system.out.println("fetching & deleting user id " + id); user user = userservice.findbyid(id); if (user == null) { system.out.println("unable delete. user id " + id + " not found"); return new responseentity<user>(httpstatus.not_found); } userservice.deleteuserbyid(id); return new responseentity<user>(httpstatus.no_content); } //------------------- delete users -------------------------------------------------------- @requestmapping(value = "/user/", method = requestmethod.delete) public responseentity<user> deleteallusers() { system.out.println("deleting users"); userservice.deleteallusers(); return new responseentity<user>(httpstatus.no_content); } }
what code change need make such can make login authentication using mongdb document name "user" instead of inmemory authentication.
Comments
Post a Comment