Announcement Announcement Module
Collapse
No announcement yet.
Problem with Rest Authentication Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Problem with Rest Authentication

    Hello everybody

    There are two apps in our development. One "app1" is an Web application that has a init form where users authenticates. And second one "app2", that is the one that allow or grant the access to the database that has all the data and users information.

    The main target that "app1" is to comunicate with "app2" to autorize or grant users after they insert their user info in a form. The idea is that user dont have to log in again during the time he is surfing our app, and that the data that he needs can be ask by "app1" asking to "app2" through REST.

    Both apps are develop using Spring 3 Framework, using Spring Security.

    Our actual test code has users storage in memory, not in database.

    For this test the restTemplate.exchange returns HttpClientErrorException: 401. We dont know if we have a mistake in the procedure, or in code.

    Thanks head.

    APP1

    Security configuration:
    PHP Code:
             <http>
            <
    form-login login-page="/login"
                        
    default-target-url="/inicio"
                        
    login-processing-url="/j_spring_security_check"
                        
    authentication-failure-url="/login?error=true" />
                        
            <
    logout logout-success-url="/home" invalidate-session="false" 
                
    delete-cookies="JSESSIONID" />
            
            <
    session-management invalid-session-url="/login?session=invalid" >
                <
    concurrency-control max-sessions="1"/>
            </
    session-management>
        </
    http>
        
        <
    authentication-manager alias="authenticationManager">
                  <
    authentication-provider ref="restAuthenticationProvider" />
        </
    authentication-manager>
        
        
        <
    beans:bean id="restAuthenticationProvider" class="com.apw.app.security.RestAuthenticationProvider" /> 
    RestAuthenticationProvider:
    PHP Code:
    public class RestAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

        @
    Autowired
        
    private RestTemplate restTemplate;
        
        public 
    RestAuthenticationProvider() {
            
    super();
            
    this.restTemplate = new RestTemplate();
        }

        @
    Override
        
    protected UserDetails retrieveUser(final String name
                final 
    UsernamePasswordAuthenticationToken authentication)
                
    throws AuthenticationException {
            
        final 
    String password authentication.getCredentials().toString();

            
    UserDetails loadedUser null;
            
            try {
               
                
    HttpHeaders headers = new HttpHeaders();
                
    String auth name ":" password;
                
    byte[] encodedAuth Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
                
    String authHeader "Basic " + new String(encodedAuth);
                
    headers.set("Authorization"authHeader);
                
    headers.setContentType(MediaType.APPLICATION_JSON);
                
    HttpEntity<Stringentity = new HttpEntity<String>(headers);

            
                
    ResponseEntity<ObjectauthenticationResponse restTemplate.exchange("http://localhost:8080/app2/rest/j_security_check"HttpMethod.POSTentityObject.class);
                
    //            GET THE AUTHORITIES OF RESPONSE AND LOADEDUSER = NEW USER(NAME,PASSWORD,TRUE,AUTHORITIES);

            
    } catch (final Exception e) {
                throw new 
    AuthenticationServiceException(e.getMessage(), e);
            }

            return 
    loadedUser;
        }

        @
    Override
        
    protected void additionalAuthenticationChecks(UserDetails arg0,
                
    UsernamePasswordAuthenticationToken arg1)
                
    throws AuthenticationException {
        } 
    Login form
    PHP Code:
    <form class="form-signin" method="post" action="<c:url value='/j_spring_security_check'/>" >
                                <
    label class="control-label">Username</label>
                                <
    div>
                                    <
    input type="text" name="j_username" class="input-block-level">
                                </
    div>
                                <
    label class="control-label">Password</label>
                                <
    div>
                                    <
    input type="password" name="j_password" class="input-block-level">
                                </
    div>
                                <
    button class="btn btn-large btn-primary" type="submit">Login</button>
                              </
    form
    APP2

    Security configuration
    PHP Code:
            <http entry-point-ref="restAuthenticationEntryPoint" use-expressions="true">
            <
    custom-filter ref="myFilter" position="FORM_LOGIN_FILTER" />
            <
    intercept-url pattern="/rest/login" access="permitAll" />
            <
    intercept-url pattern="/rest/api" access="hasRole('ROLE_ADMIN')" />
            <
    logout />
        </
    http>
        
        <
    beans:bean id="restAuthenticationEntryPoint" class="com.iec.apc.security.RestAuthenticationEntryPoint"/>
     
        <
    beans:bean id="myFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
            <
    beans:property name="filterProcessesUrl" value="/rest/j_security_check" />
            <
    beans:property name="authenticationManager" ref="authenticationManager" />
             <
    beans:property name="authenticationSuccessHandler">
                <
    beans:bean class="com.iec.apc.security.RestAuthenticationSuccessHandler" />
            </
    beans:property>
            <
    beans:property name="authenticationFailureHandler">
                <
    beans:bean class="com.iec.apc.security.RestAuthenticationFailureHandler" />
            </
    beans:property>
       </
    beans:bean>
                             
          <
    authentication-manager alias="authenticationManager">
            <
    authentication-provider user-service-ref="userService" />
        </
    authentication-manager>
        
        <
    user-service id="userService">
            <
    user name="admin" password="admin" authorities="ROLE_ADMIN"/>
        </
    user-service>
    </
    beans:beans
    And specific class for RestAuthenticationEntryPoint, restAuthenticationFailureHandler y RestAuthenticationSuccessHandler

    PHP Code:
    public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

        @
    Override
        
    public void commence(HttpServletRequest requestHttpServletResponse response,
                
    AuthenticationException authExceptionthrows IOExceptionServletException {
            
            
    response.sendError(HttpServletResponse.SC_UNAUTHORIZEDauthException.getMessage());
            
        }

    PHP Code:
    public class RestAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

        private 
    RequestMatcher requestMatcher = new ELRequestMatcher("hasHeader('X-Requested-With','XMLHttpRequest')");
         
        public 
    void setRequestMatcher(RequestMatcher requestMatcher) {
            
    this.requestMatcher requestMatcher;
        }
     
        @
    Override
        
    public void onAuthenticationSuccess(HttpServletRequest requestHttpServletResponse responseAuthentication authenticationthrows IOExceptionServletException {
            if(
    isRestRequest(requestresponseauthentication)) {
                
    response.setStatus(HttpServletResponse.SC_OK);
                
    response.getWriter().flush();
            }else {
                
    super.onAuthenticationSuccess(requestresponseauthentication);
            }
        }
     
        protected 
    boolean isRestRequest(HttpServletRequest requestHttpServletResponse responseAuthentication authentication) {
            return 
    requestMatcher.matches(request);
        }

    PHP Code:
    public class RestAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

        private 
    RequestMatcher requestMatcher = new ELRequestMatcher("hasHeader('X-Requested-With','XMLHttpRequest')");
         
        public 
    void setRequestMatcher(RequestMatcher requestMatcher) {
            
    this.requestMatcher requestMatcher;
        }
     
        @
    Override
        
    public void onAuthenticationFailure(HttpServletRequest requestHttpServletResponse responseAuthenticationException exceptionthrows IOExceptionServletException {
            if(
    isRestRequest(requestresponse)) {
                
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }else {
                
    super.onAuthenticationFailure(requestresponseexception);
            }
        }
     
        protected 
    boolean isRestRequest(HttpServletRequest requestHttpServletResponse response) {
            return 
    requestMatcher.matches(request);
        }

Working...
X