2016-02-28 15 views
6

Próbuję zmienić JHipster, więc używa obiektu JSON do uwierzytelniania zamiast parametrów formularza. Udało mi się to zrobić za jego mechanizm uwierzytelniania JWT. Teraz chciałbym to zrobić dla innych opcji uwierzytelniania.Jak uczynić Spring Security akceptować JSON zamiast parametrów formularza?

Czy istnieje prosty sposób na zmianę domyślnej konfiguracji zabezpieczeń Spring Security, aby na to zezwolić? Oto co JHipster używa teraz:

.and() 
    .rememberMe() 
    .rememberMeServices(rememberMeServices) 
    .rememberMeParameter("remember-me") 
    .key(env.getProperty("jhipster.security.rememberme.key")) 
.and() 
    .formLogin() 
    .loginProcessingUrl("/api/authentication") 
    .successHandler(ajaxAuthenticationSuccessHandler) 
    .failureHandler(ajaxAuthenticationFailureHandler) 
    .usernameParameter("j_username") 
    .passwordParameter("j_password") 
    .permitAll() 

Chciałbym wysłać następujące jako JSON zamiast parametrów forma:

{username: "admin", password: "admin", rememberMe: true} 

Odpowiedz

1

Zrobiłem takiego rodzaju rzeczy. Rozwiązanie nie jest trudne, ale udało mi się stworzyć niestandardowy filtr bezpieczeństwa oparty głównie na UserNamePasswordAuthenticationFilter.

Właściwie należy zastąpić metodę methodAuthentication. Tylko przesłonięcie metody uzyskiwaniaPassword i uzyskiwania nazwyUżytkownika może nie być możliwe, ponieważ chcesz odczytać treść żądania i musisz zrobić to jednocześnie dla obu parametrów (jeśli nie tworzysz typu wielowątkowego opakowania HttpServletRequest):

Rozwiązanie musi być tak:

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

    UsernamePasswordAuthenticationToken authRequest = 
      this.getUserNamePasswordAuthenticationToken(request); 

      // Allow subclasses to set the "details" property 
      setDetails(request, authRequest); 

      return this.getAuthenticationManager().authenticate(authRequest); 
     } 
     //[...] 

protected UserNamePasswordAuthenticationToken(HttpServletRequest request){ 
    // here read the request body and retrieve the params to create a UserNamePasswordAuthenticationToken. You may use jackson of whatever you like most 
} 
//[...] 
} 

Następnie należy go skonfigurować. I zawsze dobrze wykorzystać konfigurację opartą xml dla tego rodzaju skomplikowanych configs,

<beans:bean id="jsonUserNamePasswordAuthenticationFilter" 
       class="xxx.yyy.JsonUserNamePasswordAuthenticationFilter"> 
      <beans:property name="authenticationFailureHandler> 
       <beans:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> 
        <!-- set the failure url to a controller request mapping returning failure response body. 
        it must be NOT secured --> 
       </beans:bean> 
      </beans:property> 
      <beans:property name="authenticationManager" ref="mainAuthenticationManager" /> 
      <beans:property name="authenticationSuccessHandler" > 
       <beans:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> 
        <!-- set the success url to a controller request mapping returning success response body. 
        it must be secured --> 
       </beans:bean> 
      </beans:property> 
     </beans:bean> 

     <security:authentication-manager id="mainAuthenticationManager">     
      <security:authentication-provider ref="yourProvider" /> 
     </security:authentication-manager> 

<security:http pattern="/login-error" security="none"/> 
    <security:http pattern="/logout" security="none"/> 

<security:http pattern="/secured-pattern/**" auto-config='false' use-expressions="false" 
     authentication-manager-ref="mainAuthenticationManager" 
     create-session="never" entry-point-ref="serviceAccessDeniedHandler"> 
     <security:intercept-url pattern="/secured-pattern/**" access="ROLE_REQUIRED" /> 
     <security:custom-filter ref="jsonUserNamePasswordAuthenticationFilter" 
      position="FORM_LOGIN_FILTER" />  
     <security:access-denied-handler ref="serviceAccessDeniedHandler"/> 
     <security:csrf disabled="true"/> 
    </security:http> 

Można utworzyć kilka dodatkowych obiektów jak dostępowego-zaprzeczył-przewodnika, ale to najłatwiejsza część rzeczy

+1

można spojrzeć na to post: https://stackoverflow.com/questions/35687148/how-to-make-spring-security-accept-json-instead-of-form-parameters#35699200 – masterdany88

+0

XML Config jest kompletnie zepsuty. Proszę odnieść się do [to pytanie zamiast] (http://stackoverflow.com/questions/19500332/spring-security-and-json-authentication). – Younes

+0

@ Younes jesteś pewien? Od czasu tej odpowiedzi minęło trochę czasu, ale została podjęta na podstawie sprawdzonego i działającego przykładu. Co dokładnie jest zepsute? Oczywiście, niektóre elementy nie są skonfigurowane, tylko tam, gdzie umieszczono znaczniki komentarza xml, ale zdecydowanie działało, gdy napisałem swoją odpowiedź: – jlumietu

Powiązane problemy