【发布时间】:2019-11-01 19:04:09
【问题描述】:
我正在开发基于 Spring Boot + Spring Security 的应用程序。我使用 jdbcAuthentication 来验证用户。我还配置了自定义登录表单。
运行应用程序后,我能够成功登录并通过浏览器获取 API 响应,但是当我尝试使用 Postman 测试 API 时,我只得到 HTML 登录页面作为响应。如何获得所需的 API json 响应?
我的配置文件:
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
System.out.println("auth manager called");
auth. jdbcAuthentication() .usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery) .dataSource(dataSource)
.passwordEncoder(noop);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("Http scurity called");
http.httpBasic().
and().
authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/registration").permitAll()
.antMatchers("/admin/**").hasAuthority("ADMIN")
.antMatchers("/db").hasAuthority("DBA")
.antMatchers("/user").hasAuthority("USER").anyRequest()
.authenticated().and().csrf().disable().formLogin()
.loginPage("/login").failureUrl("/login?error=true")
.successHandler(customSuccessHandler)
.usernameParameter("username")
.passwordParameter("password")
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and().exceptionHandling()
.accessDeniedPage("/access-denied");
}
我的控制器文件:
@RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
public ModelAndView login() {
System.out.println("/login called");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
return modelAndView;
}
@RequestMapping(value = "/admin", method = RequestMethod.GET, produces = { "application/json" })
public UserUniconnect home(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String currentUser = null;
if (!(auth instanceof AnonymousAuthenticationToken)) {
currentUser = auth.getName();
}
User user1 = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
user1.getAuthorities();
System.out.println("++++++++++++++++++++++++++++++");
System.out.println(request == null);
Users u = (Users) request.getSession(false).getAttribute("user");
Uniconnect uni = (Uniconnect) request.getSession(false).getAttribute("uniconnect");
UserUniconnect uu = new UserUniconnect();
uu.setUser(u);
uu.setUniconnect(uni);
return uu;
}
我返回 java 对象作为 Spring Boot 能够将其转换为 json 格式的响应。
【问题讨论】:
标签: java spring-boot authentication postman