简体   繁体   English

Spring Security REST授权

[英]Spring Security REST authorization

I'm tired to find how I can login by Spring Security REST json. 我很累,无法找到如何通过Spring Security REST json登录。 I write backend for Android/iOS.Here is my security.xml: 我为Android / iOS编写后端,这是我的security.xml:

<http use-expressions="true" create-session="stateless" entry-point-ref="restAuthenticationEntryPoint">        
        <intercept-url pattern="/auth/**" access="permitAll" />
        <intercept-url pattern="/**" access="isAuthenticated()" />      
        <custom-filter ref="myFilter" position="FORM_LOGIN_FILTER"/>  
        <logout />               
    </http> 

    <beans:bean id="myFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
          <beans:property name="authenticationManager" ref="authenticationManager"/>
          <beans:property name="authenticationSuccessHandler" ref="mySuccessHandler"/>
    </beans:bean>
    <beans:bean id="mySuccessHandler" class="com.teamodc.jee.webmail.security.MySavedRequestAwareAuthenticationSuccessHandler"/>


    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="userDetailsService" />   
        <authentication-provider ref="authenticationProvider" />
    </authentication-manager> 

    <beans:bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="userDetailsService"/>
    </beans:bean> 

This is my AuthenticationController: 这是我的AuthenticationController:

@Controller
@RequestMapping(value = "/auth")
public class AuthorizationController {

    @Autowired
    @Qualifier(value = "authenticationManager")
    AuthenticationManager authenticationManager;

    private SimpleGrantedAuthority anonymousRole = new SimpleGrantedAuthority("ROLE_ANONYMOUS");

    @RequestMapping(value = "/login", method = RequestMethod.POST, headers = {"Accept=application/json"})
    @ResponseBody
    public Map<String, String> login(@RequestParam("login") String username, @RequestParam("password") String password) {
        Map<String, String> response = new HashMap<String, String>();


            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

            try {
                Authentication auth = authenticationManager.authenticate(token);
                SecurityContextHolder.getContext().setAuthentication(auth);

                response.put("status", "true");             
                return response;
            } catch (BadCredentialsException ex) {
                System.out.println("Login 3");
                response.put("status", "false");
                response.put("error", "Bad credentials");
                return response;
            }
        }

And finally, my web.xml: 最后,我的web.xml:

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/appServlet/servlet-context.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/dispatcher.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>charsetFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>charsetFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>   

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

I have tested it from Firefox rest client, but when I set the URL is bla/user/1 then it took me 401 (it's right), but when URL is bla/auth/login it took me 404, and return WARN [org.springframework.web.servlet.PageNotFound] - But how it can be when I marked path in @Controller 我已经从Firefox rest client测试了它,但是当我将URL设置为bla / user / 1时,我带了401(是正确的),但是当URL是bla / auth / login时,我带了404,并返回WARN [org .springframework.web.servlet.PageNotFound]-但是当我在@Controller中标记路径时如何

Your login() method seems to be mapped to /auth/auth/login . 您的login()方法似乎已映射到/auth/auth/login The path given on the method level @RequestMapping annotation is relative to that of the class level annotation. 在方法级别@RequestMapping注释上给定的路径是相对于类级别注释的路径。

Try changing the method level annotation to @RequestMapping(value = "/login"... . 尝试将方法级别注释更改为@RequestMapping(value = "/login"...

Edit: 编辑:
If that was just a typo, and you still have problems with handler mapping, then make sure that you have the appropriate instructions in your spring context: 如果那只是一个错字,而处理程序映射仍然存在问题,那么请确保在您的spring上下文中有适当的说明:

  1. <context:component-scan base-package="package.for.controllers"/> in order to have your controllers instantiated as spring beans. <context:component-scan base-package="package.for.controllers"/> ,以便将您的控制器实例化为spring bean。
  2. <mvc:annotation-driven/> in order to have support for @RequestMapping annotated controller methods. <mvc:annotation-driven/>为了支持@RequestMapping注释的控制器方法。 See the reference docs for more info. 有关更多信息,请参见参考文档

Also, make sure these are actually in the same context (normally in servlet context). 另外,请确保它们实际上在同一上下文中(通常在servlet上下文中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM