Protecting the Spring API RESTful webservice from unauthorized access?

I have successfully created a Spring RESTful web service with various APIs. Now I have to protect them from unauthorized access. I followed http://www.beingjavaguys.com/2014/10/spring-security-oauth2-integration.html and the login logic is completely different from mine. Can someone help me move on?

Receive user login request

@RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody @ResponseStatus(HttpStatus.OK) public UserResponse login(@RequestBody final UserLoginRequest userRequest) throws ServletException, IOException { UserResponse userResponse = new UserResponse(); try { userResponse = accessService.login(userRequest); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return userResponse; } 

Request user login request

  @Transactional public UserResponse login(UserLoginRequest userRequest) throws SQLException, ClassNotFoundException, IOException { UserResponse userResponse = new UserResponse(); int status = 0; //boolean isExist = loginDao.isUserExist(userRequest.getUsername(), userRequest.getPassword()); User user = loginDao.getUser(userRequest.getEmailID()); if (user != null) { if (userRequest.getPassword().equals(user.getPassword())) {//Case sensitive password and added to check status //User exist if (user.getStatus().equals("1")) { //Device token check loginDao.isDeviceTokenExists(userRequest, user.getProfileId()); status = 2; } else { status = 3; } } else { status = 4; } } else { status = 1; } if (status == 1) { userResponse.setCode(WeekenterConstants.USER_EMAIL_EXIST_CODE); userResponse.setMessage("User does not exists.Please Register."); } else if (status == 2) { userResponse.setCode(WeekenterConstants.SUCCESS_CODE); userResponse.setMessage("User login success"); userResponse.setId(user.getProfileId()); } else if (status == 3) { userResponse.setCode(WeekenterConstants.FAILURE_CODE); userResponse.setMessage("Your Account is blocked. Please contact Weekenter administrator."); userResponse.setId(user.getProfileId()); } else if (status == 4) { userResponse.setCode(WeekenterConstants.FAILURE_CODE); userResponse.setMessage("Password is wrong."); userResponse.setId(user.getProfileId()); } return userResponse; } 

I have an API for sample countries, a list of users, etc. These services should only provide data to the Android client after the user is valid. I know that authentication will be processed using an access token. How can I do this in a standard way?

+5
source share
2 answers

You can follow the specified guide by changing the login of the logic in your service.define user authentication service in your spring-security.xml .

Typically, a simple Spring Security enabled application will use simple user service as an authentication source:

 <!--Custom User details service which is provide the user data--> <bean id="customUserDetailsService" class="com.yourpackage.CustomUserDetailsService" /> <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="customUserDetailsService" /> </authentication-manager> 

Your customUserDetailsService should implement a UserDetailsService available at org.springframework.security.core.userdetails.UserDetailsService

 import com.weekenter.www.dao.LoginDao; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional(readOnly = true) public class CustomUserDetailsService implements UserDetailsService { @Autowired private LoginDao loginDao; public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException { boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; com.weekenter.www.entity.User user = null; try { user = loginDao.getUser(login);//login variable contain your requested username if (user != null) { if (user.getStatus().equals("1")) { enabled = false; } } else { throw new UsernameNotFoundException(login + " Not found !"); } } catch (Exception ex) { try { throw new Exception(ex.getMessage()); } catch (Exception ex1) { } } <!-- Password comparison will happen here --> return new User( user.getEmail(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities() ); } public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authList = getGrantedAuthorities(getRoles()); return authList; } public List<String> getRoles() { List<String> roles = new ArrayList<String>(); roles.add("ROLE_APP"); return roles; } public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); for (String role : roles) { authorities.add(new SimpleGrantedAuthority(role)); } return authorities; } } 

Finally, in spring-security.xml you can filter the secure urls as below

 <!-- This is where we tells spring security what URL should be protected and what roles have access to them --> <http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security"> <anonymous enabled="false" /> <intercept-url pattern="/api/**" access="ROLE_APP" /> <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /> <access-denied-handler ref="oauthAccessDeniedHandler" /> </http> 
0
source

I think you need to have a separate process that will authorize the device for use in your application.

I was working on an application in which tablets are registered to use the application. The tablet ID is stored in a simple text file available for the Apache server. Then all REST requests have a special header X_DEVICEID, which contains the device identifier, and the PHP script used by Apache to check this identifier in the file will only respond if the identifier is intended for the registered device.

The allowed device identifier file acts as a kind of firewall to block unregistered devices.

+1
source

All Articles