I've created rest-api with BasicAuthenticationEntryPoint. It looks like this
@Component
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
//response.addHeader("WWW-Authenticate", "Basic realm=" +getRealmName());
response.addHeader("WWW-Authenticate", "FormBased");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authException.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("Marketplace");
super.afterPropertiesSet();
}
}
As you have noticed I'm using "FormBased" header in order avoid browser's ugly authorization window. Front-end Angular application uses its own authorization form. It works fine, but I'm also using Swagger as self describing tool for rest-api. With Swagger and such header ( response.addHeader("WWW-Authenticate", "FormBased");
) I have a problem. Swagger returns 401 error because browser do not suggests authorization window. Is there any way use Swagger with header ( response.addHeader("WWW-Authenticate", "FormBased")
;) instead of ( response.addHeader("WWW-Authenticate", "Basic realm=" +getRealmName());
)?
I've found solution for this problem. The point is that I had wrong security configuration in WebSecurityConfigurerAdapter
. The configuration secured any request like this
http.csrf().disable().authorizeRequests()
.antMatchers("/api/registration/**").permitAll()
.antMatchers("/api/dictionary/**").permitAll()
.antMatchers("/api/common/**").permitAll()
.antMatchers("/api/advert_public/**").permitAll()
.antMatchers("/api/company_public/**").permitAll()
.anyRequest().hasRole(DEFAULT_ROLE)
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);
And this way Swagger entry point required login/password too.
Now I've rewrote configuration to secure particular methods in my api and Swagger works fine
http.csrf().disable().authorizeRequests()
.antMatchers("/api/advert/**").hasRole(DEFAULT_ROLE)
.antMatchers("/api/company/**").hasRole(DEFAULT_ROLE)
.antMatchers("/api/user/**").hasRole(DEFAULT_ROLE)
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);
As you could see there is no config option like .anyRequest().hasRole(DEFAULT_ROLE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.