2016-09-01 1 views
1

Я использую версию Spring 4.3.1.RELEASE и ее пользовательское приложение для входа в систему аутентификации. Но я столкнулся вопросИмя пользователя и пароль не сопоставляются с аутентификацией весной

Сначала посмотрим на код

CustomAuthenticationProvider.java

@Component 
@Qualifier(value = "customAuthenticationProvider") 
public class CustomAuthenticationProvider implements AuthenticationProvider{ 


public Authentication authenticate(Authentication authentication) throws  AuthenticationException { 
    String username = authentication.getName(); 
    String password = (String) authentication.getCredentials(); 
    User user = new User(); 
    user.setUsername(username); 
    user.setPassword(password); 


    Role r = new Role(); 
    r.setName("ROLE_ADMIN"); 
    List<Role> roles = new ArrayList<Role>(); 
    roles.add(r); 


    Collection<? extends GrantedAuthority> authorities = roles; 
    return new UsernamePasswordAuthenticationToken(user, password, authorities); 
} 

public boolean supports(Class<?> arg0) { 
    return true; 
} 

} 

SecurityConfiguration.java

@Configuration 
@EnableWebSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

@Autowired 
private CustomAuthenticationProvider customAuthenticationProvider; 

@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.authenticationProvider(customAuthenticationProvider); 
} 

//.csrf() is optional, enabled by default, if using  WebSecurityConfigurerAdapter constructor 
@Override 
protected void configure(HttpSecurity http) throws Exception { 

    http.authorizeRequests() 
      .antMatchers("/admin/**").access("hasRole('ROLE_USER')") 
      .and() 
      .formLogin() 
      .loginPage("/login").failureUrl("/login?error") 
      .usernameParameter("username").passwordParameter("password") 
      .and() 
      .logout().logoutSuccessUrl("/login?logout") 
      .and() 
      .csrf(); 
} 
} 

login.jsp Вот мой Логин страница

<form name="loginForm" novalidate ng-submit="ctrl.login(user)"> 
     <div class="form-group" ng-class="{'has-error': loginForm.username.$invalid}"> 
      <input class="form-control" name="username" id="username" type="text" 
        placeholder="Username" required ng-model="user.username" /> 
      <span class="help-block" 
        ng-show="loginForm.username.$error.required">Required</span> 
     </div> 
     <div class="form-group" ng-class="{'has-error': loginForm.password.$invalid}"> 
      <input class="form-control" name="password" id="password" type="password" 
        placeholder="Password" required ng-model="user.password" /> 
      <span class="help-block" 
        ng-show="loginForm.password.$error.required">Required</span> 
     </div> 
     <div class="form-group"> 
      <button type="submit" class="btn btn-primary pull-right" 
        value="Login" title="Login" ng-disabled="!loginForm.$valid"> 
       <span>Login</span> 
      </button> 
     </div> 
    </form> 

На Authenticate() в классе CustomAuhtenticationProvider

  1. authentication.getCredentials();
  2. authentication.getName();

оба пустые строки, но мне нужно имя пользователя и пароль.

Here is IntellijIdea Debug screen shot

Вот мой AngularJS служба

Service.js

function loginUser(user) { 
    var config = { 
     headers: { 
      'csrf_token': csrfToken 
     } 
    } 


    var deferred = $q.defer(); 
    $http.post("/login", user,config) 
     .then(
      function (response) { 
       deferred.resolve(response.data); 
      }, 
      function(errResponse){ 
       console.error('Error while creating User'); 
       deferred.reject(errResponse); 
      } 
     ); 
    return deferred.promise; 
} 
+0

На самом деле я использую AngularJS, и он включен в сервис –

+1

Uhm ... как вы отправляете имя пользователя и пароль? Общие параметры формы или в любом другом формате, таком как json? – jlumietu

+1

Я знаю, поэтому я сказал вам попробовать отключить csrf(), так как в форме не отображается токен csrf. Как сказал @ M.Deinum, включите свой угловой контроллер или сдайте в аренду формат сообщения для запроса на вход. Бьюсь об заклад, вы отправляете json – jlumietu

ответ

0

Вы отправляете учетные данные в формате JSON и используется по умолчанию UsernamePasswordAuthenticationFilter, который пытается получить аутентификацию учетные данные из параметров HttpServletRequest.

Они всегда будут иметь значение null. Вы должны создать свой собственный фильтр, который принимает учетные данные для проверки подлинности из json, полученных в теле запроса, а не из параметров http.

Посмотрите this

EDIT: Дело в том, что вы не получаете регистрационные данные вы отправленные с угловыми контроллера. Вероятно, причина в том, что если вы отправляете их как json в тело запроса, вы не можете полагаться на файл UsernamePasswordAuthenticationFilter по умолчанию, поскольку он пытается создать объект аутентификации, считывая параметры HttpServletRequest.

общественного класс UsernamePasswordAuthenticationFilter расширяет AbstractAuthenticationProcessingFilter {

public Authentication attemptAuthentication(HttpServletRequest request, 
      HttpServletResponse response) throws AuthenticationException { 
     if (postOnly && !request.getMethod().equals("POST")) { 
      throw new AuthenticationServiceException(
        "Authentication method not supported: " + request.getMethod()); 
     } 

     String username = obtainUsername(request); 
     String password = obtainPassword(request); 
     ... 
} 

/** 
    * Enables subclasses to override the composition of the password, such as by 
    * including additional values and a separator. 
    * <p> 
    * This might be used for example if a postcode/zipcode was required in addition to 
    * the password. A delimiter such as a pipe (|) should be used to separate the 
    * password and extended value(s). The <code>AuthenticationDao</code> will need to 
    * generate the expected password in a corresponding manner. 
    * </p> 
    * 
    * @param request so that request attributes can be retrieved 
    * 
    * @return the password that will be presented in the <code>Authentication</code> 
    * request token to the <code>AuthenticationManager</code> 
    */ 
    protected String obtainPassword(HttpServletRequest request) { 
     return request.getParameter(passwordParameter); 
    } 

    /** 
    * Enables subclasses to override the composition of the username, such as by 
    * including additional values and a separator. 
    * 
    * @param request so that request attributes can be retrieved 
    * 
    * @return the username that will be presented in the <code>Authentication</code> 
    * request token to the <code>AuthenticationManager</code> 
    */ 
    protected String obtainUsername(HttpServletRequest request) { 
     return request.getParameter(usernameParameter); 
    } 

Вы должны расширить этот фильтр, переопределить attemptAuthentication() метод, чтобы избежать вызова obtainUsername и obtainPassword при восстановлении этого полномочия. Вместо этого напишите собственный метод, в котором вы прочитаете ServletRequest's InputStream и проанализируете объект, используя библиотеку json, к которой вы привыкли.Я обычно использую jackson this way

+0

Взгляните на прикрепленное изображение, я не получаю нулевое значение, это пустая строка. –

Смежные вопросы