Can I have multiple Configurations in Spring Security for securing web application and Rest API?

后端 未结 2 1079
心在旅途
心在旅途 2020-12-19 12:19

I\'m trying to create REST API and web/MVC application in Spring. They both should use the same service layer. Can I somehow use two completely different configurations in S

2条回答
  •  温柔的废话
    2020-12-19 13:00

    You can write a rest controller and normal controller for all endpoints. Spring security will automatically add an auth flow when you add it, and if you want to override you can do that in the configuration.

    Rest Controller for /api/foo

    @RestController
    @RequestMapping("/api/foo")
    public class FooRestController {
      //All the methods must conform to a rest api
      @GetMapping
      public String fooGet() {
        return "foo"; // this will return foo as string
      }
    }
    

    Normal controller for /ui/foo

    @Controller
    @RequestMapping("/ui/foo")
    public class FooController {
       @RequestMapping(method = RequestMethod.GET) // You can use @GetMapping
        public ModelView homePage(Model model) {
          // set model attributes
          return "home"; // this will be mapped to home view jsp/thyme/html
        }
    
    }
    

    This way you can separate cookie logic and manage redirects and validations, in the normal controller.

提交回复
热议问题