I have two tables 'user' and 'role'.I want to create a login api (e.g '/login') which will take username and password as a json data. I want to check if given credential is a valid credential and if it is,then I want to set the user as authenticated user so that he/she may have the protected resources. I am new to spring boot framework and I don't know how to do so.I have read the offical documentation but cannot find any resources.Could someone help me on this?
- 1use spring-security role based authorization. this link might help you to some extentharshavmb– harshavmb2017-06-13 03:07:35 +00:00Commented Jun 13, 2017 at 3:07
- @harshavmb thank you very much.Your link was very much helpful.Ramesh Khadka– Ramesh Khadka2017-06-13 16:35:45 +00:00Commented Jun 13, 2017 at 16:35
1 Answer
You have number of choices to implement such authentication in Spring.
Case 1:- If you are building REST services then you can implement security in following ways:
i) - you can use Basic-Authentication to authenticate your user.
ii) - you can use OAuth2 to authenticate and authorize your user.
Case 2: If you are building web application
i) - you can use auth token (in case of Single page application SPA)
ii) - you can use session based authentication (traditional login form and all)
I Guess you are in beginner mode so i will recommend you to firstly understand the control flow user authentication in web app via login form. So Let's go through some code.
I'm assuming that you have set a basic spring project and now you are implementing security.
USER - Hibernate entity for your user table; ROLE - Hibernate entity for your role table
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthProvider customAuthProvider; @Override protected void configure(HttpSecurity http) throws Exception { // everyone is allowed tp view login page http.authorizeRequests().antMatchers("/login").permitAll().and(); http.authorizeRequests().antMatchers("custom_base_path" + "**").authenticated().and(). formLogin().loginPage("/loginForm).loginProcessingUrl("/loginUser") .usernameParameter("username").passwordParameter("password") .defaultSuccessUrl("custom_base_path+ "home", true); @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(customAuthProvider); } //CustomAuthProvider @Component public class CustomAuthentiationProvider implements AuthenticationProvider{ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String userid = authentication.getName(); String password = authentication.getCredentials().toString(); Authentication auth = null; try { //write your custom logic to match username, password boolean userExists = your_method_that_checks_username_and_password if(userExists ){ List<Role> roleList= roleDao.getRoleList(userid); if (roleList == null || roleList.isEmpty()) { throw new NoRoleAssignedException("No roles is assigned to "+userid); } auth = new UsernamePasswordAuthenticationToken(userid, password,getGrantedAuthorities(roleList)); } } catch (Exception e) { log.error("error", e); } return auth; } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } public List<GrantedAuthority> getGrantedAuthorities(List<Role> roleList) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); for (Role role : roleList) { authorities.add(new SimpleGrantedAuthority(role.getRoleName()); } return authorities; } } NOTE: Please consider these codes to understand the logic of authentication. don't consider as perfect code(Not for production env.). You can ping me anytime i'll suggest you more about that.