【问题标题】:Spring Boot Authorizes User In Rest Client, But Not In Browser (Rest Authorization)Spring Boot 在 Rest Client 中授权用户,但不在浏览器中授权(Rest Authorization)
【发布时间】:2016-02-21 20:30:51
【问题描述】:

好的,所以当我使用我的 Rest Client (Insomnia) 时。我能够登录到我的 Spring Server 并在之后成功检索数据。

但是当我尝试使用我的 angularJS 客户端时。我可以成功登录,但是当我尝试检索数据时,它会发回 401 错误,就好像它忘记了我曾经登录过一样。我很困惑。

您可能会注意到代码中的 X-AUTH-TOKEN。截至目前,我没有设置它检查 X-AUTH-TOKEN 的位置,因此请忽略这一点,请注意它在我的 REST 客户端中有效,但在浏览器客户端中无效。

我什至尝试在我的 REST CLIENT 中添加与浏览器客户端相同数量的请求标头信息,但它仍会为其检索数据。

下面是我的 WebSecurityConfig

package app.config;

import app.repo.User.CustomUserDetailsService;
import app.security.RESTAuthenticationEntryPoint;
import app.security.RESTAuthenticationFailureHandler;
import app.security.RESTAuthenticationSuccessHandler;
import app.security.TokenAuthenticationService;
import app.security.filters.StatelessAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@Order(2)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static PasswordEncoder encoder;
    @Autowired
    private TokenAuthenticationService tokenAuthenticationService;

    private CustomUserDetailsService userService;

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Autowired
    private RESTAuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private RESTAuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private RESTAuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    public void configureAuth(AuthenticationManagerBuilder auth,DataSource dataSource) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").authenticated();
        http.csrf().disable();
        http.httpBasic();
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
        http.formLogin().defaultSuccessUrl("/").successHandler(authenticationSuccessHandler);
        http.formLogin().failureHandler(authenticationFailureHandler);

//        http.addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
//                UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService);
    }

    @Bean
    @Override
    public CustomUserDetailsService userDetailsService() {
        return userService;
    }

    @Bean
    public TokenAuthenticationService tokenAuthenticationService() {
        this.userService = new CustomUserDetailsService();
        tokenAuthenticationService = new TokenAuthenticationService("tooManySecrets", customUserDetailsService);
        return tokenAuthenticationService;
    }
}

我也有一个 CorsFilter

package app.config;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CorsFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(CorsFilter.class);

    public CorsFilter() {
        log.info("SimpleCORSFilter init");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Expose-Headers", "X-Auth-Token");
        response.setHeader("Access-Control-Allow-Headers",
                "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

为什么Spring登录后接受我的Spring Requests,但我登录后不接受我的Client Request。

我检查用户是否通过持久数据库进行身份验证

package app.repo.User;

import app.cache.UserService;
import app.security.UserAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
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;

import java.util.*;

@Service
@Qualifier("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepo userRepository;

    @Autowired
    private UserService userService;

    private final AccountStatusUserDetailsChecker detailsChecker = new AccountStatusUserDetailsChecker();
    private final HashMap<String, User> userMap = new HashMap<String, User>();

    @Transactional(readOnly=true)
    @Override
    public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {

        app.repo.User.User user = userRepository.findByUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("Bad Credentials");
        }
        userService.setUserInfo(user);
        List<GrantedAuthority> authorities = buildUserAuthority(user.getRoles());
        UserDetails userDetails = buildUserForAuthentication(user, authorities);
//        detailsChecker.check(userDetails);
        return userDetails;

    }

    private UserDetails buildUserForAuthentication(app.repo.User.User user,
                                            List<GrantedAuthority> authorities) {
        return new User(user.getUsername(), user.getPassword(), authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (UserRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getRoleName()));
        }

        return new ArrayList<GrantedAuthority>(setAuths);
    }

    public void addUser(User user) {
        userMap.put(user.getUsername(), user);
    }
}

这是我的浏览器登录请求标头

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:0
Host:localhost:8080
Origin:http://localhost:8100
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36

这里是浏览器登录的响应头

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Accept, X-Requested-With, remember-me
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin:http://localhost:8100
Access-Control-Expose-Headers:X-Auth-Token
Access-Control-Max-Age:3600
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:88
Date:Thu, 19 Nov 2015 16:22:39 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Set-Cookie:JSESSIONID=966F22A08A6D30E73FDC0DF40749C5C2; Path=/; HttpOnly
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

这是在浏览器中检索数据的请求标头

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:0
Host:localhost:8080
Origin:http://localhost:8100
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36

在浏览器中检索数据数据的响应头

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Accept, X-Requested-With, remember-me
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin:http://localhost:8100
Access-Control-Expose-Headers:X-Auth-Token
Access-Control-Max-Age:3600
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Thu, 19 Nov 2015 16:25:03 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

对于我的休息客户。响应标头相同。对于 Rest Client 的请求标头,它没有任何显示。但我尝试将完全相同的标头添加到 Rest Client,它仍然有效。

这是我的 angularjs 调用

$http({
  method: 'POST',
  url: loginUrl
}).then(function successCallback(response) {
  var resp = response;
  $http({
    method: 'POST',
    url: $scope.siteUrl+'/get-all-games'
  }).then(function successCallback(response) {
    var resp = response;
      // this callback will be called asynchronously
      // when the response is available
  }, function errorCallback(response) {
    var resp = response;
      // called asynchronously if an error occurs
      // or server returns response with an error status.
  });
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
  var resp = response;
    // called asynchronously if an error occurs
    // or server returns response with an error status.
}); 

我设置了我的 $http 调用,以便在登录成功后立即调用以检索数据...即使我成功登录,它仍然返回 401 错误。

【问题讨论】:

  • 我为登录和检索数据添加了请求和响应标头。感谢您的帮助
  • 我正在单步执行代码,看起来它仍然认为我的客户是匿名的,尽管我已经登录了。我也添加了我的 $http 调用。我将它设置在成功登录后立即调用数据的位置。仍然返回 401
  • 所以我猜我的客户休息会自动保存这个。我希望我的 REST 客户端向我展示我的请求标头。我可能会想出来的。不过我会检查一下。谢谢
  • 我还要确保您在会话中保持身份验证?通常 REST 客户端会在没有持久性的情况下使用基本身份验证(我看到你确实启用了)(因此在每个请求的基本身份验证标头中发送用户名/密码)。如果您没有持久性设置,那么您的登录表单将在发送时进行身份验证,但不会在将来的请求中进行。我在您的代码 sn-ps 中没有看到 SecurityContextPersistenceFilter。
  • 那你是在使用命名空间配置吗?此外,您可以使用 fiddler 之类的代理来查看您的其余标题。

标签: java angularjs spring spring-security spring-boot


【解决方案1】:

凭据信息(在这种情况下为 cookie/会话 ID)应与您在浏览器中检索数据的请求一起携带。 可以像下面这样配置 Angular 客户端。

$httpProvider.defaults.withCredentials = true;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-15
    • 2019-02-10
    • 2021-04-07
    • 2016-12-20
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多