Blazor RoleClaims Policy Not Working on Api end point - asp.net-core

I have application authorizing users based on role claims they owned.
I have following set up
I. Server Side
I have registered policy for startup class
services.AddAuthorization(options =>
{
options.AddPolicy(Permissions.Products.Create, policy => policy.RequireClaim("Permissions", Permissions.Products.Create));
options.AddPolicy(Permissions.Products.Edit, policy => policy.RequireClaim("Permissions", Permissions.Products.Edit));
options.AddPolicy(Permissions.Products.View, policy => policy.RequireClaim("Permissions", Permissions.Products.View));
options.AddPolicy(Permissions.Products.Delete, policy => policy.RequireClaim("Permissions", Permissions.Products.Delete));
});
This is the api controller method.
// GET: api/Products
[HttpGet]
[Authorize (Policy = Permissions.Products.View)]
public async Task<ActionResult<List<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
This is my blazor component
#page "/product-list"
#inject HttpClient client
#inject IJSRuntime js
<h3>Products</h3>
<small>Add as many products as you wish.</small>
<div class="form-group">
<a class="btn btn-success" href="product/create"><i class="oi oi-plus"></i> Create New</a>
</div>
<br>
#if (products == null)
{
<text>Loading...</text>
}
else if (products.Length == 0)
{
<text>No Records Found.</text>
}
else
{
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (Product product in products)
{
<tr>
<td>#product.Id</td>
<td>#product.Name</td>
<td>#product.Type</td>
<td>
<a class="btn btn-success" href="product/edit/#product.Id">Edit</a>
<button class="btn btn-danger" #onclick="#(() => Delete(product.Id))">Delete</button>
</td>
</tr>
}
</tbody>
</table>
}
#code {
Product[] products { get; set; }
protected override async Task OnInitializedAsync()
{
products = await client.GetFromJsonAsync<Product[]>("api/products");
}
async Task Delete(int productId)
{
var product = products.First(x => x.Id == productId);
if (await js.InvokeAsync<bool>("confirm", $"Do you want to delete {product.Name}'s ({product.Id}) Record?"))
{
await client.DeleteAsync($"api/products/{productId}");
await OnInitializedAsync();
}
}
}
Then, I tested by login into superuser which grants all permissions (claims).
I get the user cookies attached to postman.
When I send the request to that controller. it resulted as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>PermissionBlazorApp</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="PermissionBlazorApp.Client.styles.css" rel="stylesheet" />
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>

Related

What is the best way to display non entity data in asp MVC View

I have a non-entity custom and raw SQL query in asp MVC controller with c#. I want to send this data to the asp MVC razor view and display them in a tabular format with their corresponding column headers. How can I get the header (the custom query can involve any number of tables) and display the data in a tabular format? I am grateful for the help.
public class QueryScriptController : Controller
{
private EntitiesContext db = new EntitiesContext();
public ActionResult CreateQueryScript(string SqlQueryString )
{
try
{
var ResultList= db.Database.SqlQuery<string>(SqlQueryString).ToList();
return View(ResultList);
}
catch
{
return View();
}
}
}
In your controller,pass the data to a Viewbag like shown below and pass that Viewbag to the razor view.
public class QueryScriptController : Controller
{
private EntitiesContext db = new EntitiesContext();
public ActionResult CreateQueryScript(string SqlQueryString )
{
try
{
var ResultList= db.Database.SqlQuery<string>
(SqlQueryString).ToList();
ViewBag.data =ResultList;
return View();
}
catch
{
return View();
}
}
}
In your razor page,call the Viewbag like shown below and call the data objects you get from the query.
#{
var data = ViewBag.data;
}
using somemodel;
<!DOCTYPE html>
<html style="position: absolute; width: 100%; height: 100%">
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Fira+Sans" rel="stylesheet">
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<title>PaySlip</title>
</head>
<body >
<div class="col-lg-6">
<h5 align="center" style="text-decoration: underline;">Results</h5>
<table className="table-bordered table-striped">
<thead>
<tr>
<th style="width: 60%">Column 1</th>
<th style="width: 30%">Column 2</th>
</tr>
</thead>
<tbody>
#foreach (var item in #data)
{
<tr >
<td style="width: 60%">#item.object1</td>
<td style="width: 30%">#item.object2</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>

Controller cannot go to server Side in mvc

I am doing my application in MVC. I have registration and Login links. I have implemented Login link in all pages. If i click login it is moving to the server side(controller) and opening. MY problem is from whatever page i click login it needs to open in the same window in popup. It means that it doesn't go the server side.
My code is
#model SYTMain.Models.Login
#{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout_for_login.cshtml";
//Layout = "~/Views/Shared/_Layout_for_login_registration .cshtml";
}
<center><h2>Login</h2></center>
<div id="dialog-modal" title="Login">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "Login failed. Check your login details.");
<div style=" margin-bottom: 400px;">
<fieldset>
<legend>Login</legend>
<div class="editor-label">
#Html.LabelFor(u => u.EmailID)
</div>
<div class="editor-field">
#Html.TextBoxFor(u => u.EmailID)
#Html.ValidationMessageFor(u => u.EmailID)
</div>
<div class="editor-label">
#Html.LabelFor(u => u.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(u => u.Password)
#Html.ValidationMessageFor(u => u.Password)
</div>
#*<div class="editor-label">
#Html.CheckBoxFor(u => u.RememberMe)
#Html.LabelFor(u => u.RememberMe)
</div>*#
<input type="submit" value="Log In" />
</fieldset>
</div>
}
</div>
Layout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
#*<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />*#
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script src="~/Scripts/Popup/jquery-1.5.1.min.js"></script>
<script src="~/Scripts/Popup/jquery-ui-1.8.11.js"></script>
#Scripts.Render("~/bundles/modernizr")
<script>
$(function () {
$("#dialog-modal").dialog({
width: 400,
height: 200,
show: {
effect: "shake",
duration: 100
},
hide: {
effect: "explode",
duration: 1000
}
});
});
</script>
</head>
<body style=" margin: 0px auto;overflow: scroll; overflow-x: hidden; /* width: 1330px; */height: auto;">
<div class="layoutouter">
<div class="layoutlogo">
#Html.ActionLink("Sell Your Time", "Index", "Home")
</div>
<div class="layoutmenu">
#if (!string.IsNullOrEmpty(Convert.ToString(Session["EmailID"])))
{
#Html.ActionLink("Signout", "Logout", "CU")
}
else
{
#Html.ActionLink("Register", "Create", "CU")
}
</div>
<br /><br />
#*<strong>Welcome #Session["EmailID"]</strong>*#
<div>
#RenderSection("featured", required: false)
</div>
</div>
<div style="width:1000px ; margin:0px auto;">
#RenderBody()
</div>
<div class="layoutfooter">
<div class="layoutfooter_data">
<div class="layout_location">
#Html.ActionLink("Change Location", "yy", "zz")
<span>|</span>
</div>
<div class="layout_feedback">
#Html.ActionLink("Feedback", "yy", "zz")
<span>|</span>
</div>
<div class="layout_help">
#Html.ActionLink("Help", "yy", "zz")
</div>
</div>
<div class="footer_copy">
<p>© #DateTime.Now.Year - acutesoftsys</p>
</div>
<div class="footer_condition">
<div class="footer_term">
<span>|</span>
#Html.ActionLink("Term & Condition", "", "")
</div>
<div class="footer_policy">
#Html.ActionLink("Privacy Policy", "yy", "zz")
</div>
</div>
</div>
#RenderSection("scripts", required: false)
</body>
</html>
My controller code is
[HttpPost, ValidateInput(false)]
public ActionResult Login(Login loginDetails)
{
if (ModelState.IsValid)
{
using (SYTEntities context = new SYTEntities())
{
var LoginUser = context.tblUsers.Where(a => a.EmailID == loginDetails.EmailID && a.Password == loginDetails.Password).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(loginDetails.EmailID, loginDetails.RememberMe);
Session["EmailID"] = LoginUser.EmailID;
Session["UserID"] = LoginUser.UserID;
return RedirectToAction("CalendarView", "Appt", new { CustomerUserid = Session["UserID"]});
// return RedirectToAction("Details/" + Session["UserID"]);
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");
}
}
}
return View(loginDetails);
}
Please help me to achieve this .
Thanks in Advance
Your controller code should look something like this
public ActionResult YourControllerAction( int Userid )
{
//Add your logic here
return PartialView( "UserDetails", model );
}
Your partial view should look like this
#model Models.Login
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>login</title>
</head>
<body>
<div>
/*Your markup here*/
</div>
</body>
</html>
Your jQuery code should look something like this.
$('#loginlinkid').on('click', function(evt) {
var $loginDiv = $('#PopUpDiv')
$.get(urlOfYourAction, function(data) {
$loginDiv.replaceWith(data);
});
//Add code to open popup here. eg..bootstrap modal dialog
});
Similar post here Render a partial view inside a Jquery modal popup on top of a parent view

How enable button when no results found datatables

<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
responsive: true
});
});
</script>
<script>
$(document).ready(function () {
$('#dataTables-example').dataTable( {
"fnDrawCallback": function( oSettings ) {
if ($(".dataTables_empty")[0]) {
$('#newclient').prop("disabled", false);
} else {
$('#newclient').prop("disabled", true);
}
}
} );
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/3cfcc339e89/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<link href="//cdn.datatables.net/plug-ins/3cfcc339e89/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet">
<link href="//cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="add-client"><button type="button" class="btn btn-primary btn-sm" id="newclient" disabled="true">Add Client</button></div>
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Name</th>
<th>File Number</th>
<th>Department</th>
<th>Date</th>
<th>User Name</th>
<th>Password</th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX">
<td>Mbello Elizabeth</td>
<td>954687</td>
<td>w547</td>
<td>October 15 2013</td>
<td>Mbello</td>
<td>cfhqsuvx</td>
</tr>
</tbody>
</table>
I'm using DataTables and I need to enable a button when no results found after searching, Any one can help me please.
Thanks
it works here but it dosen't work in my page, I don't know what is the problem
You could use the DataTables draw callback to find out if there are no results in the current table. fnDrawCallback
This is a simple fiddle to check how to enable a button after searching with no results.
Javascript:
$(document).ready(function () {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
if ($(".dataTables_empty")[0]) {
$('#test').prop("disabled", false);
} else {
$('#test').prop("disabled", true);
}
}
} );
});

How to get a rating value in asp.net mvc4?

I am new asp.net mvc4 with entity frame work, I have designed rating in cshtml file,Pls help me to get a rated value in Controller. Thanks in advance.
This is my cshtml code for rating
{
#{
ViewBag.Title = "Index";
}
<h2>Index rating</h2>
<h2>rating</h2>
#*<form method="post" id="signin" action="#Url.Action("rating", "Rating")">*#
#if (Request.IsAuthenticated)
{
<form method="post" id="signin" action="#Url.Action("rating", "Rating")">
<p>
#DateTime.Now
</p>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="~/Scripts/jquery.js"></script>
<script type="text/javascript" src="~/Scripts/rating.js"></script>
<link rel="stylesheet" type="text/css" href="~/Styles/rating.css" />
<script type="text/javascript">
$(function () {
$('.rating').rating();
$('.ratingEvent').rating({ rateEnd: function (v) { $('#result').text(v); } });
});
</script>
<input type="text" class="ratingEvent rating5" #*id="result"*# value="rating" />
<div><b id="result">5</b> start(s)</div>
<p> </p>
</form>
}
}
This is my Controller code
{
[HttpGet]
public ActionResult rating(int ratedvalue)
{
using (var db = new Project.Models.EntitiesContext())
{
var value= new Project.Models.Tbl_Rating();
var rat = db.Tbl_Rating.FirstOrDefault(u => u.Rating == ratedvalue);
value.Rating = Convert.ToInt32(rat);
return View();
}
}
}
}
try like this
View:
<form method="post" id="signin" action="#Url.Action("rating", "Rating")">
**YOUR CODE**
<input type="text" class="ratingEvent rating5" name="rating" value="rating" /> //Add name attribute
<input type="submit" />
</form>
Controller:
public ActionResult rating(FormCollection form)
{
int ratedvalue=form["rating"]
}

SignalR client script runs only in index page

I'm developing an MVC 4 web application and using signalR library to make a real time notification system.
I have a working script that I use in master page called _Layout.cshtml.
here's the script in _Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="~/signalr/hubs"></script>
</head>
<body >
<header dir="rtl">
<table align="center" cellpadding="0" cellspacing="0" style="width:100%;">
<tr>
<td style="width:30%; height:40px;" valign="top"><img src="~/Images/header_logo3.png" /></td>
<td style="width: 40%; height: 40px; " valign="top"> <a href='#Url.Action("Index","Home")'><img class="header_logo" src='#Url.Content("~/Images/header_logo2.png")' /></a></td>
<td style="width: 30%; height: 40px; " valign="top" ><img src="~/Images/header_logo4.png" /></td>
</tr>
</table>
<h2>Index</h2>
<span id="mySpanTag"></span>
<script type="text/javascript">
//var notificationHub = $.connection.notificationHub;
$(function () {
//Create Hub on Air
var chat = $.connection.notificationHub;
//Messages
$messages = $("#mySpanTag");
//Client Side Method To Access From Server Side Method
chat.client.sendMessage = function (msg) {
$messages.html(msg);
}
$.connection.hub.start(function () {
chat.server.sendMessage("Hello World!");
});
});
</script>
</header>
<div id="wrapper" dir="rtl">
<div id="Smenu" class="visible">
#{Html.RenderAction("Menu", "SettingsMenu", new { id = "nir"});}
</div>
#RenderSection("JavaScript", false)
<section>
#RenderBody()
</section>
</div>
<footer></footer>
</body>
</html>
the Hub class:
using System.Web;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace HaifanetMobile.Hubs
{
public class NotificationHub : Hub
{
public void SendMessage(string msg)
{
Clients.All.sendMessage(msg);
}
}
}
Everything goes ok and I see the massage method called from the hub class in my page, except that
this script is running only on the index.cshtml (startup page) and not in all the web pages in the project or in a specific one of them. e.g not working and the script is the same as you can see:
#model schoolnetMobile.Models.UserModel
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<span id="mySpanTag"></span>
<script type="text/javascript">
//var notificationHub = $.connection.notificationHub;
$(function () {
//Create Hub on Air
var chat = $.connection.notificationHub;
//Messages
$messages = $("#mySpanTag");
//Client Side Method To Access From Server Side Method
chat.client.sendMessage = function (msg) {
$messages.html(msg);
}
$.connection.hub.start(function () {
chat.server.sendMessage("Hello World!");
});
});
</script>
<br /><br />
#if (Request.IsAuthenticated) {
<h4>profile: #Model.UserName</h4>
if (User.Identity.Name == #Model.UserName)
{
<br />
<ul style="list-style-type: none;">
<li>first name: #Model.FirstName;</li>
<li>username: #Model.UserName</li>
<li>schoolname: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
else
{
<br />
<ul style="list-style-type: none;">
<li>username: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
}
else
{
<h4>need to login</h4>
}
Update: I placed the script only if detail.cshtml. Looks like
there is a problem in this line
var chat = $.connection.notificationHub;
as only the first alert("hi") pops up and not the second...
#model HaifanetMobile.Models.UserModel
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Scripts
{
<script type="text/javascript">
$(function () {
//Create Hub on Air
alert("hi");
var chat = $.connection.notificationHub;
alert("hi1");
//Messages
$messages = $("#messages");
alert("hi2");
//Client Side Method To Access From Server Side Method
chat.client.addMessage = function (frm, msg) {
$messages.append("<br /><b>" + frm + ":</b>" + msg);
}
alert("hi3");
$("#txtMsg").keypress(function (e) {
//when enter
if (e.which == 13) {
alert("hi4");
//get value of input
var input = $(this).val();
//send message to "Server Side Method"
chat.server.sendMessage("#Session.SessionID", input);
//Reset TextBox
$(this).val("");
}
});
//Hub Starting
$.connection.hub.start();
});
</script>
}
<div>Your ID: #Session.SessionID</div>
<input type="text" id="txtMsg" />
<div id="messages">
</div>
<h2>Index</h2>
<span id="mySpanTag"></span>
<br /><br />
#if (Request.IsAuthenticated) {
<h4>user profile: #Model.UserName</h4>
if (User.Identity.Name == #Model.UserName)
{
<br />
<ul style="list-style-type: none;">
<li>first name: #Model.FirstName;</li>
<li>user name: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
else
{
<br />
<ul style="list-style-type: none;">
<li>username: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
}
else
{
<h4>Please login</h4>
}