从未经过自动化访问保护Spring RESTful Web服务API?

时间:2015-07-14 05:26:31

标签: android web-services spring-mvc spring-security

我已成功创建了一个包含不同API的Spring RESTful Web服务。现在我应该保护他们免受未经授权的访问我跟着http://www.beingjavaguys.com/2014/10/spring-security-oauth2-integration.html,登录逻辑与我的完全不同。有人可以帮助我继续前进吗?

获取用户登录请求

 @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;
    }

处理用户登录请求

 @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;
    }

我有获取国家/地区的API,用户列表等。一旦用户有效,这些服务应该只向Android客户端提供数据。我知道将使用访问令牌处理身份验证。我怎么能以标准的方式做到这一点?

2 个答案:

答案 0 :(得分:1)

我认为您需要一个单独的流程来授权设备在您的应用程序中使用。

我参与了一个使用应用程序注册平板电脑的应用程序。平板电脑ID保存在Apache服务器可访问的简单文本文件中。然后,所有REST请求都有一个特殊的头X_DEVICEID,其中包含设备ID,Apache使用的PHP脚本在文件中检查此ID,并且只有在ID用于注册设备时才会给出响应。

允许的设备ID文件充当一种阻止未注册设备的防火墙。

答案 1 :(得分:0)

  

您可以通过更改登录来遵循上述教程本身   service.define中的自定义身份验证服务   customUserDetailsService

     

通常,一个简单的启用Spring Security的应用程序会使用a   简单的用户服务作为身份验证源:

UserDetailsService
  

您的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; } }   可用   spring-security.xml

<!-- 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>
  

最后在{{1}}中,您可以过滤受保护的网址   如下所示

{{1}}