I translate the project from spring to spring boot. the last thing left to do is configure the security.

I tried to do as here but failed XML configuration of Spring Security in Spring Boot

I have

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">

<http entry-point-ref="restAuthenticationEntryPoint">
    <intercept-url pattern="/com/bt**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
    <intercept-url pattern="/com/bt/db/**" access="permitAll()" />
    <form-login login-page="/login" login-processing-url="/j_spring_security_check"
        authentication-success-handler-ref="successHandler"
        authentication-failure-handler-ref="failureHandler" />
    <csrf disabled="true" />
    <!-- <headers> <frame-options disabled="true"/> <hsts disabled="true"/> 
        <cache-control disabled="true"/> </headers> -->
    <logout />
</http>

<beans:bean id="successHandler" class="com.bt.AjaxAuthSuccessHandler" />
<beans:bean id="failureHandler"
    class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />

<authentication-manager alias="authenticationManager">
    <authentication-provider>
        <password-encoder hash="bcrypt" />
        <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="select username,password, enabled from users where username=?"
            authorities-by-username-query="select username, role from user_roles where username =?" />
    </authentication-provider>
</authentication-manager>

and this entity

@Entity
@Table(name="users", schema="public")
public class User {

@Id
private String username;

@Column(name="password")
private String password;

@Column(name="enabled")
private boolean enabled;
@OneToMany(mappedBy="user")
private List<UserRole> userRoles;
}

class which is used in app-context-security.xml

public class AjaxAuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

public AjaxAuthSuccessHandler() {
    super();
    setRedirectStrategy(new NoRedirectStrategy());
}

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    super.onAuthenticationSuccess(request, response, authentication);
    Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF8");
    response.getWriter().print("{\"role\": \""+authorities.toArray()[0]+"\"}");
}

protected class NoRedirectStrategy implements RedirectStrategy {

    @Override
    public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
            throws IOException {
        // no redirect

    }

}

}

UPDATE: I was create second entity with roles

@Entity
@Table(name="user_role", schema="public")
public class UserRole {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Integer id;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "username")
private User user;

@Column(name="role")
private String role;

and repository for this entity. created service

@Service
public class UserService implements UserDetailsService {

@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

    User user = userRepository.findById(name)
            .orElseThrow( () -> new UsernameNotFoundException("Invalid username or password"));
    return new org.springframework.security.core.userdetails.User(user.getUsername(),
            user.getPassword(),
            mapRolesToAuthorities(user.getQueuesManagers()));
}

private Collection<? extends GrantedAuthority> mapRolesToAuthorities(List<UserQueueManager> roles){
    return roles.stream()
            .map(role -> new SimpleGrantedAuthority(role.getRole()))
            .collect(Collectors.toList());
}
}

based on these classes created a configuration file

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter    {

@Autowired
private UserService userService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Bean
public BCryptPasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
}

@Bean
public DaoAuthenticationProvider authenticationProvider(){
    DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
    auth.setUserDetailsService(userService);
    auth.setPasswordEncoder(passwordEncoder());
    return auth;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider());
}
}

but for some reason it doesn't work :( UPD 2:

20:22:14.564 [http-nio-8080-exec-5] DEBUG           org.springframework.web.servlet.DispatcherServlet - GET      "/ETP.MQ.WEB.CONSOLE/components/select2/select2.min.css", parameters={}
20:22:14.564 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/angular-ui-router.min.js", parameters={}
20:22:14.564 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/jquery/dist/js/jquery.min.js", parameters={}
20:22:14.564 [http-nio-8080-exec-9] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/angular-cookies/angular-cookies.js", parameters={}
20:22:14.564 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/js/bootstrap.min.js", parameters={}
20:22:14.564 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/angular-datatables/angular-datatables.min.js", parameters={}
20:22:14.569 [http-nio-8080-exec-9] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/angular-cookies/angular-cookies.js
20:22:14.569 [http-nio-8080-exec-7] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/js/bootstrap.min.js
20:22:14.569 [http-nio-8080-exec-8] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/angular-datatables/angular-datatables.min.js
20:22:14.569 [http-nio-8080-exec-10] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/angular-ui-router.min.js
20:22:14.569 [http-nio-8080-exec-6] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/jquery/dist/js/jquery.min.js
20:22:14.569 [http-nio-8080-exec-5] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/select2/select2.min.css
20:22:14.570 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-9] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.570 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.584 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2", parameters={}
20:22:14.585 [http-nio-8080-exec-1] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2
20:22:14.585 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.590 [http-nio-8080-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff", parameters={}
20:22:14.590 [http-nio-8080-exec-2] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff
20:22:14.591 [http-nio-8080-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.595 [http-nio-8080-exec-3] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf", parameters={}
20:22:14.596 [http-nio-8080-exec-3] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf
20:22:14.596 [http-nio-8080-exec-3] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
20:22:14.601 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg", parameters={}
20:22:14.602 [http-nio-8080-exec-4] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /ETP.MQ.WEB.CONSOLE/components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg
20:22:14.602 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND

the stricture of my project: enter image description here

and configuration class

@Configuration
public class WebMvcConfigure implements WebMvcConfigurer {

@Bean
public ViewResolver getViewResolver() {
    InternalResourceViewResolver resolver
            = new InternalResourceViewResolver();
    resolver.setPrefix("/*");
    resolver.setSuffix("*.jsp");
    return resolver;
}

@Override
public void configureDefaultServletHandling(
        DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/webapp/**")
            .addResourceLocations("/webapp/").setCachePeriod(3600)
            .resourceChain(true).addResolver(new PathResourceResolver());
}
}

LAST UPDATE

    <servlet>
    <servlet-name>page-resolver</servlet-name>
    <servlet-class>com.bk.ForwardServlet</servlet-class>
    <init-param>
        <param-name>page</param-name>
        <param-value>/index.jsp</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>page-resolver</servlet-name>
    <url-pattern>/index.html</url-pattern>
    <url-pattern>/login</url-pattern>
    <url-pattern>/qmgr/*</url-pattern>
</servlet-mapping>

0 Answers