使用Basic Auth对另一个应用程序验证Springboot应用程序

时间:2017-09-13 18:57:04

标签: java rest spring-boot spring-security basic-authentication

如何针对第三方应用程序验证Spring Boot应用程序?

根据使用spring security实现基本身份验证的示例,验证用户和密码,但我想验证来自其他服务的200响应。 以下是用户身份验证的方式: 用户使用Basic Auth发送凭据以访问我的SpringBoot REST服务 - > SpringBoot服务向第三方服务发出带有基本身份验证标头的GET请求 - >收到200 OK并验证最终用户访问我的REST服务上的所有URL。

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPoint authEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .anyRequest().authenticated()
                .and().httpBasic()
                .authenticationEntryPoint(authEntryPoint);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }

}

2 个答案:

答案 0 :(得分:1)

您必须实施自己的AuthenticationProvider。例如:

public class ThirdPartyAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication auth) thows AuthenticationException {
        // call third party site with auth.getPrincipal() and auth.getCredentials() (those are username and password)
        // Throw AuthenticationException if response is not 200
        return new UsernamePasswordAuthenticationToken(...);
    }

    @Override
    public boolen supports(Class<?> authCls) {
        return UsernamePasswordAuthenticationToken.class.equals(authCls);
    }
}

之后,您可以覆盖SpringSecurityConfig

中的configure(AuthenticationManagerBuilder)方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // authProvider = instance of ThirdPartyAuthenticationProvider
    auth.authenticationProvider(authProvider); 
}

答案 1 :(得分:0)

我使用UserDetailsS​​ervice让它工作。我创建了一个休息模板并调用我的第三方服务来验证用户,并在收到响应后,用户可以访问所有请求。我就这样做了:

SecurityConfig.java

    @Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPoint authEntryPoint;

    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic()
                .authenticationEntryPoint(authEntryPoint);

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService)
            throws Exception {

        auth.userDetailsService(userDetailsService);
    }

ABCUserDetails.java

    @Service("userDetailsService")
public class ABCUserDetails implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String abcuser) throws UsernameNotFoundException {
        // TODO Auto-generated method stub

        Map<String, Object> userMap = userService.getUserByUsername(abcuser);

        // check if this user with this username exists, if not, throw an
        // exception
        // and stop the login process
        if (userMap == null) {
            throw new UsernameNotFoundException("User details not found : " + abcuser);
        }

        String username = (String) userMap.get("username");
        String password = (String) userMap.get("password");
        String role = (String) userMap.get("role");

        List<SimpleGrantedAuthority> authList = getAuthorities(role);

        User user = new User(username, password, authList);

        return user;

    }

    private List<SimpleGrantedAuthority> getAuthorities(String role) {
        List<SimpleGrantedAuthority> authList = new ArrayList<>();
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));

        if (role != null && role.trim().length() > 0) {
            if (role.equals("myrole")) {
                authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
        }

        return authList;
    }
}

UserService.java

@Service("userService")
public class UserService {

    public Map<String, Object> getUserByUsername(String username) {
        // TODO Auto-generated method stub

        Map<String, Object> userMap = null;
//get current request attributes
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

        String authToken = attr.getRequest().getHeader("Authorization");
        final String encodedUserPassword = authToken.replaceFirst("Basic" + " ", "");
        String usernameAndPassword = null;
        try {
            byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
            usernameAndPassword = new String(decodedBytes, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
        final String username1 = tokenizer.nextToken();
        final String password = tokenizer.nextToken();
//thirdparty url
        final String uri = "http://abcurlauthprovider/userid="
                + "\"" + username1 + "\"";

        RestTemplate restTemplate = new RestTemplate();
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("Authorization", "Basic " + encodedUserPassword);
            HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
            ResponseEntity<String> mresponse = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

            if (username.equals(username1) || username.equals(username1)) {
                userMap = new HashMap<>();
                userMap.put("username", username1);
                userMap.put("password", password);
                userMap.put("role", (username.equals(username1)) ? username1 : username1);
                // return the usermap
                return userMap;
            }
        } catch (Exception eek) {
            System.out.println("** Exception: " + eek.getMessage());
        }

        return null;
    }

}

这是我的AuthenticatioEntryPoint.java

    @Component
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
            throws IOException, ServletException {

        response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 - " + authEx.getMessage());

    }

    @Override
    public void afterPropertiesSet() throws Exception {

        System.out.println("----------------------inside afterPropertiesSet method");
        setRealmName("MYAPI");
        super.afterPropertiesSet();
    }}
相关问题