0

package com.project.agro.service;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.project.agro.model.Role;
import com.project.agro.model.User;
import com.project.agro.repos.UserRepository;

import java.util.HashSet;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService{
    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username);
        if (user == null) throw new UsernameNotFoundException(username);

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Role role : user.getRoles()){
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}
package com.project.agro.service;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.project.agro.model.Role;
import com.project.agro.model.User;
import com.project.agro.repos.UserRepository;

import java.util.HashSet;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService{
    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username);
        if (user == null) throw new UsernameNotFoundException(username);

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Role role : user.getRoles()){
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
  <link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
      <link href="${contextPath}/resources/css/style.css" rel="stylesheet">
      <link href="${contextPath}/resources/css/fixed.css" rel="stylesheet">

</head>
<body>

<%@ include file="common/navbar.jsp"%>

 <div class="container-fluid">
  
  
  <div class="row">
  
  <div class="col-3">
  <div class="side-nav">
   <nav>
    <ul>
     <li><a href="#"> <span>Title</span></a></li>
                   <li><a href="crops.html"> <span>Crops</span></a></li>
     <li class="active"><a href="fertilizer.html"> <span>Fertilizer</span></a></li>
     <li><a href="#"> <span>Agro News</span></a></li>
    </ul>
   </nav>
  </div>
  </div>
  <div class="col-9">
   <form class="form-horizontal" action="/admin/crop/addcrop"
    method="post"  enctype="multipart/form-data" style="margin-top:5rem;" >
    <fieldset>
     <legend class="center-block">
      New crop Information
     </legend>

     
     <!-- title -->
     <div class="form-group" style="display:flex;">
      <label class="col-sm-2 control-label" for="title">Crop Name</label>

      <div class="col-sm-8">
       <input type="text" name="cName" class="form-control" id="cName"
         required="required" placeholder="Title" /> 
      </div>
     </div>

     <!-- author -->
     <div class="form-group" style="display:flex;">
      <label class="col-md-2 control-label" for="cScientificName">
       Scientific Name</label>
      <div class="col-md-8">
       <input type="text" name="cScientificName" class="form-control"
        id="cScientificName" required="required"
        placeholder="Scientific Name" />
      </div>
     </div>



     <!-- description -->
     <div class="form-group" style="display:flex;">
      <label class="col-md-2 control-label" for="description">Description</label>
      <div class="col-md-8">
       <textarea name="description" rows="5" class="form-control"
        id="description" placeholder="Description"></textarea>
      </div>
     </div>

     <!-- upload image -->
     <div class="form-group" style="display:flex;">
      <div class="col-md-2">
       <label for="cImage">Upload crop image</label>
      </div>
      <div class="col-md-8">
       <input id="cImage" type="file" name="cImage" value="cImage" />
      </div>
     </div>

     <!-- description -->
     <div class="form-group" style="display:flex;">
      <label class="col-md-2 control-label" for="description">Associated
       Disease</label>
      <div class="col-md-8">
       <input type="text" name="associatedDisease" class="form-control"
        id="description" 
        placeholder="Associated Disease" /> 
      </div>
     </div>

     <div class="form-group" style="display:flex;">
      <div class="col-md-2"></div>
      <div class="col-md-8">
       <button type="submit" class="btn btn-success">Add Book</button>
       <a class="btn btn-danger" href="">Cancel</a>
      </div>
     </div>
    </fieldset>
   </form>
   </div>
  </div>
 </div>
   <script src="${contextPath}/resources/js/bootstrap.min.js" ></script>
 <script src="${contextPath}/resources/js/jquery-3.3.1.min.js" ></script>

</body>
</html>
    -
package com.project.agro;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasAuthority("ADMIN")
                .antMatchers("/resources/**", "/registration","/home").permitAll()
                .anyRequest().authenticated()
                .and()

            .formLogin()
                .loginPage("/login")
                .permitAll().defaultSuccessUrl("/welcome")
                .and()
            .logout()
                .permitAll();
    }

    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
        return authenticationManager();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}
package com.project.agro.controller;



import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.project.agro.model.Crop;
import com.project.agro.service.CropService;



@Controller
public class CropController {

    @Autowired
    private CropService cropService;

    @RequestMapping(value="/admin/crop/addcrop" ,method = RequestMethod.GET)
    public String addcrop(Model model) {
        Crop crop = new Crop();
        model.addAttribute("crop", crop);
        return "addcrop";
    }

    @RequestMapping(value="/admin/crop/addcrop" , method = RequestMethod.POST)
    public  String addcroppost(@ModelAttribute(value="crop") Crop crop ,HttpServletRequest request){
        cropService.save(crop);
        MultipartFile cImage=crop.getcImage();
        try {
            byte[] bytes = cImage.getBytes();
            String name = crop.getCropID() + ".png";
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File("src/main/webapp/image/crop/" + name)));
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/cropList";



    }

    @RequestMapping("/cropList")
    public String cropList(Model model) {
        /*List<Book> bookList = bookService.findAll();*/

        return "cropList";

    }
}

I am trying to build an web application using Spring Boot and Spring Security.I am submitting a form with POST method as an admin to add some details into database but everytime I hit that submit button it shows the error page.I have added all the dependencies .The registration and login page works fine What am I suppose to do here?

  • 2
    Hi, we need a little bit more infos, what is your config? didi you just added spring security as dependency? without any code is difficoult to understand the situation – rick Aug 15 '19 at 08:16
  • Yeah ,I have added spring security dependency in my pom.xml – Quail UriBI Aug 15 '19 at 08:17
  • You need to be logged and have the ADMIN authority in order to reach /admin/** endpoint. What is the desired behaviour? – rick Aug 15 '19 at 08:58
  • I am trying to add some data into the database.I can successfully login as an admin and access the url "/admin/crop/addcrop" but whenever i hit that submit button it shows the forbidden 403 error – Quail UriBI Aug 15 '19 at 09:31
  • do you set the role ADMIN or authority in your UserDetailService? ( can you post it?) – rick Aug 15 '19 at 11:05
  • Hey Rick ,I have added it – Quail UriBI Aug 15 '19 at 11:28
  • If the user that comes out of the UserDetail service as the authority ADMIN(all caps) it should work. Strange. I tested locally with a pseudo app and it works – rick Aug 15 '19 at 11:48
  • Might help to [enable Spring security logging](https://stackoverflow.com/questions/30855252/how-do-i-enable-logging-for-spring-security). It will tell you exactly why authentication fails. – Christopher Schneider Aug 15 '19 at 15:27
  • I somehow solved the problem by disabling csrf(which is not recommended as i read online ) .Thanks anyway ! – Quail UriBI Aug 16 '19 at 02:53

0 Answers0