处理错误:InvalidGrantException,凭据错误

时间:2018-10-18 11:46:44

标签: java spring-boot

包com.phynart.cloud.config;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
    import org.springframework.security.oauth2.provider.token.TokenStore;
    import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
    import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

        private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerConfig.class);

        static final String CLIEN_ID = "devglan-client";
        static final String CLIENT_SECRET = "devglan-secret";   
        static final String GRANT_TYPE_PASSWORD = "password";
        static final String AUTHORIZATION_CODE = "authorization_code";
        static final String REFRESH_TOKEN = "refresh_token";
        static final String IMPLICIT = "implicit";
        static final String SCOPE_READ = "read";
        static final String SCOPE_WRITE = "write";
        static final String TRUST = "trust";
        static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60*60;
        static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60;

        @Autowired
        private AuthenticationManager authenticationManager;

        @Bean
        public JwtAccessTokenConverter accessTokenConverter() {
            logger.debug("in access token converter");
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            converter.setSigningKey("as466gf");
            return converter;
        }

        @Bean
        public TokenStore tokenStore() {
            logger.debug("tokenStore");
            return new JwtTokenStore(accessTokenConverter());
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
            logger.debug("ClientDetailsServiceConfigurer");
            configurer
                    .inMemory()
                    .withClient(CLIEN_ID)
                    .secret(CLIENT_SECRET)
                    .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
                    .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)                     
                    .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
                    .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            logger.debug("AuthorizationServerEndpointsConfigurer");
            endpoints.tokenStore(tokenStore())
                    .authenticationManager(authenticationManager)
                    .accessTokenConverter(accessTokenConverter());
        }
    }

package com.phynart.cloud.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ResourceServerConfig.class);

    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        logger.debug("ResourceServerSecurityConfigurer");
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        logger.debug("HttpSecurity resource");
        http.
                anonymous().disable()
                .authorizeRequests()
                .antMatchers("/users/**").access("hasRole('ADMIN')")
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }    

}


package com.phynart.cloud.config;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

    @Resource(name = "UserService")
    private UserDetailsService userDetailsService;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        logger.debug("inside authentication manager");
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        logger.debug("password encoder");
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(encoder());    
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        logger.debug("HttpSecurity");
        http
                .csrf().disable()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/api-docs/**").permitAll();
    }

    @Bean
    public BCryptPasswordEncoder encoder(){
        logger.debug("inside password encoder");
        // return new BCryptPasswordEncoder();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        logger.debug("bCryptPasswordEncoder -" + bCryptPasswordEncoder);
        return bCryptPasswordEncoder;
    }    


    @Bean
    public FilterRegistrationBean corsFilter() {
        logger.debug("corsFilter");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}


package com.phynart.cloud.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.phynart.cloud.model.User;
import com.phynart.cloud.service.UserService;
import java.security.Principal;

@RestController
@RequestMapping("/users")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired    
    private UserService userService;

    @RequestMapping(value="/user", method = RequestMethod.GET)
    public Iterable<User> listUser(){
        logger.debug("inside controller");
        return userService.findAll();
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public User create(@RequestBody User user){
        return userService.save(user);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable(value = "id") Long id){
        userService.delete(id);
        return "success";
    }

}


package com.phynart.cloud.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 com.phynart.cloud.dao.UserDao;
import com.phynart.cloud.model.User;

@Service(value = "UserService")
public class UserServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        logger.debug("loadUserByUsername");
        User user = userDao.findByUsername(userId);
        if(user == null){
            throw new UsernameNotFoundException("Invalid username or password.");
        }
        logger.debug("before returning user");
        logger.debug("username -" + user.getUsername());
        logger.debug("password -" + user.getPassword());        
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthority());

    }

    private List getAuthority() {
        return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
    }

    public List findAll() {
        logger.debug("findAll");
        List list = new ArrayList<>();
        userDao.findAll().iterator().forEachRemaining(list::add);
        return list;
    }
}

package com.phynart.cloud.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import com.phynart.cloud.dao.UserDao;
import com.phynart.cloud.model.User;

@Service
public class UserService {

    @Autowired
    UserDao userDao;

    public Iterable<User> findAll() {

        return userDao.findAll();
    }

    public User save(User user) {

        return userDao.save(user);
    }

    public void delete(Long id) {
        // TODO Auto-generated method stub

    }

}

我收到错误的凭据“处理错误:InvalidGrantException,错误的凭据”,即使我注释了BCryptPasswordEncoder部分并在数据库中使用普通密码仍然面临问题,有人可以帮助我吗?我没有找到任何解决方案,并且是oauth实施的新手,  我添加了AuthorizartionServerConfig,ResourceServerConfig,SecurityConfig,UserServiceImpl,UserController-我已经从站点中提取了代码-https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example

basic auth from postman

Body in postman for user credetial

database credential of the user

data entered from the site i coded - https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example

1 个答案:

答案 0 :(得分:0)

我认为您输入用户凭据的参数有误。
body in postman for user credentials

  item | type
   A   |  1  
   B   |  2  
   A   |  3   
   C   |  4  
   B   |  5   
   A   |  6   

代替

  item | type
   A   |  1  
   B   |  2  
   A   |  1   
   C   |  3  
   B   |  2   
   A   |  1
相关问题